nish
nish

Reputation: 7280

How to get the output of python script executed from a ruby method

I am trying to run a python script from ruby method. I am running this method as a rake task within a Rails app. I am using the solution mentioned here:

def create
    path = File.expand_path('../../../../GetOrders', __FILE__)
    output = `"python2 " + path + "/parse.py"`
    print output
    str = JSON.parse(output)
    print str
end

EDIT: This works:

    output = `python2 #{path}/parse.py`

EDIT2: Using the python script i am trying to pass a list of dictionaries to the ruby function. The python script looks something like:

import xml.etree.ElementTree as ET
import json

def parse():
    tree = ET.parse('response.xml')
    root = tree.getroot()
    namespaces = {'resp': 'urn:ebay:apis:eBLBaseComponents'}
    order_array = root.find("resp:OrderArray", namespaces=namespaces)
    detailsList = []
    for condition:
        details["key1"] = value1
        details["key2"] = value2
    detailsList.append(details)
    output = json.dumps(detailsList)
    return output

print parse()

Could someone explain what i am doing wrong and how can I fix this. Thanks

Upvotes: 0

Views: 1894

Answers (3)

Alp
Alp

Reputation: 2826

When you do this:

output = `python2 #{path}/parse.py`

output will be assigned the standard output of the python script, but that script isn't writing anything to standard output; the json data that's the return value of the parse() call is simply discarded. You seem to be expecting the execution of the script to have a "return value" that's the return value of the script's last expression, but that's not how processes work.

You probably want to replace the parse() call at the end of the script with print parse().

Upvotes: 1

David Grayson
David Grayson

Reputation: 87416

Imagine typing this exact string:

"python2 " + path + "/parse.py"

into your shell (e.g. bash). It would look for a program named "python2 " and give it four arguments

+
path
+
/parse.y

You can't put arbitrary Ruby code inside a backtick string the same way you can't put arbitrary code in normals strings. You must use string interpolation.

Upvotes: 1

whatyouhide
whatyouhide

Reputation: 16781

You are calling this exact line on the shell:

"python2 -path- /parse.py"

which the shell interprets as a single command: python2 (with a space at the end).

Try using string interpolation, which works with the backtick operator:

output = `python2 #{path}/parse.py`

Upvotes: 1

Related Questions