user1251007
user1251007

Reputation: 16721

Get return value of ruby function in python

I have a ruby script that gets executed by a python script. From within the python script I want to access to return value of the ruby function.

Imagine, I would have this ruby script test.rb:

class TestClass
    def self.test_function(some_var)
        if case1
            puts "This may take some time"
            # something is done here with some_var
            puts "Finished"
        else
            # just do something short with some_var
        end
        return some_var
    end
end

Now, I want to get the return value of that function into my python script, the printed output should go to stdout.

I tried the following (example 1):

from subprocess import call
answer = call(["ruby", "-r", "test.rb", "-e", "puts TestClass.test_function('some meaningful text')"])

However, this gives me the whole output on stdout and answer is just the exit code.

Therefore i tried this (example 2):

from subprocess import check_output
answer = check_output(["ruby", "-r", "test.rb", "-e", "puts TestClass.test_function('some meaningful text')"])

This gives me the return value of the function in the else case (see test.rb) almost immediately. However, if case1 is true, answer contains the whole output, but while running test.rb nothing gets printed.

Is there any way to get the return value of the ruby function and the statements printed to stdout? Ideally, the solution requires no additional modules to install. Furthermore, I can't change the ruby code.

Edit:

Also tried this, but this also gives no output on stdout while running the ruby script (example 3):

import subprocess
process = subprocess.Popen(["ruby", "-r", "test.rb", "-e", "puts TestClass.test_function('some meaningful text')"], stdout=subprocess.PIPE)
answer = process.communicate()

I also think that this is no matter of flushing the output to stdout in the ruby script. Example 1 gives me the output immediately.

Upvotes: 0

Views: 651

Answers (2)

jsbueno
jsbueno

Reputation: 110311

Another way of doing this, without trying to call the ruby script as an external process is to set up a xmlrpc (or jsonrpc) server with the Ruby script, and call the remote functions from Python jsonrpc client (or xmlrpc)- the value would be available inside the Python program, nad even the sntax used would be just like you were dealing with a normal Python function.

Setting up such a server to expose a couple of functions remotely is very easy in Python, and should be the same from Ruby, but I had never tried it.

Upvotes: 1

user1277476
user1277476

Reputation: 2909

Check out http://docs.python.org/library/subprocess.html#popen-constructor and look into the ruby means of flushing stdout.

Upvotes: 0

Related Questions