I'm trying to use the RubyPython module (https://github.com/halostatue/rubypython) to execute Python code from within a Ruby script. I have the module all set up correctly, but am very confused how to use it.
If I had a block of Python code as text, say:
def multiply(x, y):
return x * y * y
z = multiply(x, y)
How would I be able to pass this to Python to execute with 'x' and 'y' defined dynamically in Ruby, and then be able to retrieve the value of 'z'?
Edit per comment request So far, this works and makes sense to me:
RubyPython.start(python_exe: "/usr/bin/python2.6")
cPickle = RubyPython.import("cPickle")
p cPickle.dumps("Testing RubyPython.").rubify
RubyPython.stop # stop the Python interpreter
That gives me an output of "S'Testing RubyPython.'\n."
And I can run very simple commands like this:
RubyPython.start(python_exe: "/usr/bin/python2.6")
x = 3
y = x * x * x
print "y = %d" % y
RubyPython.stop # stop the Python interpreter
That gives me an output of "y = 27"
, as expected.
But once I try to define a method in python, I just get a series of errors:
RubyPython.start(python_exe: "/usr/bin/python2.6")
def my_multiply(x, y):
return x * y * y
z = my_multiply(2, 3)
print "z = %d" % z
RubyPython.stop # stop the Python interpreter
I get syntax error, unexpected ':'
So how would I execute this block of python code using this module? And more importantly, how would I pass values in from Ruby into the Python code that is executing?
Since no answer has been made, and I managed to find something (although a very ugly something at that).
I'm not sure at all if this is the intended method to use RubyPython
but I was able to get things to function by doing the following set of tasks:
> RubyPython.start
> RubyPython::Python.PyRun_SimpleString <<-PYTHON
*> def test():
*> print("Hello, World")
*> PYTHON
> main = RubyPython.import("__main__")
> main.test()
>>> Hello, World!
> RubyPython::Python.PyRun_SimpleString <<-PYTHON
*> def my_mult(x, y):
*> return x * y
*> PYTHON
> main.my_mult(10, 20).rubify
>>> 200
Again, whether this is the "correct" way to do it, or not is up for debate - but it worked.