Eric
Eric

Reputation: 2018

How do I invoke Python code from Ruby?

Does a easy to use Ruby to Python bridge exist? Or am I better off using system()?

Upvotes: 5

Views: 6703

Answers (5)

user1935929
user1935929

Reputation: 21

If you want to use Python code like your Python script is a function, try IO.popen .

If you wanted to reverse each string in an array using the python script "reverse.py", your ruby code would be as follows.

strings = ["hello", "my", "name", "is", "jimmy"]
#IO.popen: 1st arg is exactly what you would type into the command line to execute your python script.
#(You can do this for non-python scripts as well.)
pythonPortal = IO.popen("python reverse.py", "w+")
pythonPortal.puts strings #anything you puts will be available to your python script from stdin
pythonPortal.close_write

reversed = []
temp = pythonPortal.gets #everything your python script writes to stdout (usually using 'print') will be available using gets
while temp!= nil
    reversed<<temp
    temp = pythonPortal.gets
end 

puts reversed

Then your python script would look something like this

import sys

def reverse(str):
    return str[::-1]

temp = sys.stdin.readlines() #Everything your ruby programs "puts" is available to python through stdin
for item in temp:
    print reverse(item[:-1]) #Everything your python script "prints" to stdout is available to the ruby script through .gets
    #[:-1] to not include the newline at the end, puts "hello" passes "hello\n" to the python script

Output: olleh ym eman si ymmij

Upvotes: 0

usr
usr

Reputation: 61

gem install rubypython

rubypython home page

Upvotes: 6

Felix
Felix

Reputation: 1090

For python code to run the interpreter needs to be launched as a process. So system() is your best option.

For calling the python code you could use RPC or network sockets, got for the simplest thing which could possibly work.

Upvotes: -1

Bayard Randel
Bayard Randel

Reputation: 10086

You could try Masaki Fukushima's library for embedding python in ruby, although it doesn't appear to be maintained. YMMV

With this library, Ruby scripts can directly call arbitrary Python modules. Both extension modules and modules written in Python can be used.

The amusingly named Unholy from the ingenious Why the Lucky Stiff might also be of use:

Compile Ruby to Python bytecode.
And, in addition, translate that
bytecode back to Python source code using Decompyle (included.)

Requires Ruby 1.9 and Python 2.5.

Upvotes: 6

Charlie Martin
Charlie Martin

Reputation: 112356

I don't think there's any way to invoke Python from Ruby without forking a process, via system() or something. The language run times are utterly diferent, they'd need to be in separate processes anyway.

Upvotes: 2

Related Questions