As part of a larger project, I’m trying to “embed” a Python interactive interpreter in a Ruby process. I’d like to be able to do something like the following:
$ irb
irb(main):001:0> pipe = IO.popen("python", "w+")
=> #<IO:0x7f3dba4977e0>
irb(main):002:0> pipe.puts "print 'hello'"
=> nil
irb(main):003:0> pipe.gets
=> 'hello\n'
Unfortunately, the gets seems to hang rather than return any kind of output from the Python process. I’ve tried variations of this procedure with open3, using mode r+ instead of w+, and a couple other minor options (python -u among them), with no success.
Is there a way to establish interactive communication with a Python shell from Ruby – in effect, to “wrap” the Python CLI? I’m using Ruby 1.8.7 (2010-06-23 patchlevel 299) and Python 2.6.6 on an x86_64 machine, though hopefully solutions will be portable(ish) across Python versions.
popendoesn’t look like a terminal to python, so you are not running in interactive mode. You can force python to start in interactive mode with-i:You’ll probably have to do some work to remove the
>>>prompt, etc.EDIT: here is the multi-line friendly version (I’m preserving the code is clear and answered the original question):