0

How can I call python running in shell from ruby. Actually I need ruby to communicate with some app running under the python in shell. So I need ruby to call python (command 'python') in cmd and then import libraries (command 'import xyz') under the python environment, and thne run functions of this imported libraries (for example 'xyz.showdate()'), and get result of course.

I tryed to use IO.popen and Open3.popen3 functions to achieve this, but I do something wrong.

Actually I use jruby on rails, but it should be same with ruby, I guess.

1
  • Hmm... does the python library work under Jython? Then you can call it as you would a Java class, avoiding the overhead of shelling out natively and running another interpreter every call. Commented Sep 3, 2012 at 0:10

1 Answer 1

2

You probably don't really want to be doing this, this is going to make your ruby script excessively convoluted when you could probably get the result directly in ruby.

If you however decide to go that way, you could create a python script that does what you need and run it from the ruby script:

# python-script.py 
import xyz
if __name__ == '__main__':
    xyz.showdate()

You would then arrange so that your ruby script calls the following command:

python path/to/python-script.py

Provided your xyz.showdate prints the date, you can collect standard output to get the result.

But again, that's probably not a great idea.

Sign up to request clarification or add additional context in comments.

2 Comments

So is there any other way how to set up communication between ruby and python shell? If I think about long term use, how about XML-RPC? Is it slow due to client-server architecture?
It might be slower, but definitely not slow. Plus, using a python daemon running your xml rpc server will save interpreter /application startup overhead, which can become a concern if you have a large selection app to load. It's obviously saner design, additionally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.