How can I draw the output of one program and use it as an input to another?

I looked through this one and it did not help.

I have a Ruby program that puts the question in the cmd line, and I would like to write a Python program that can return the answer. Does anyone know of any links or even how I can do this?

Thank you for your help.

EDIT
Thanks to the guys who mentioned piping . I did not use it too much and was glad that he was raised, as it made me look too much into it.

+4
python ruby io
source share
5 answers
p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) ruby_question = p.stdout.readline() answer = calculate_answer(ruby_question) p.stdin.write(answer) print p.communicate()[0] # prints further info ruby may show. 

The last two lines can be made into one:

 print p.communicate(answer)[0] 
+10
source share

If you are using unix / linux, you can use the pipeline:

 question.rb | answer.py 

Then the output of question.rb becomes the input of answer.py

I have not tried this recently, but I have the feeling that the syntax can work on Windows as well.

+4
source share

Pexpect

http://www.noah.org/wiki/Pexpect

Pexpect is pure Python waiting module. Pexpect makes Python a better tool for managing other applications.

Pexpect is a clean Python module for spawning baby apps; their control; and responding to expected patterns in their products. Pexpect works as Don Libes expected. Pexpect allows your script to spawn a child application and control it as if a person were entering commands.

+3
source share

First of all, check this: [Unix pipeing] [1]

It works with windows or unix, but it is weaker than dufferent, first the program:

question.rb:

 puts "This is the question" 

answer.rb:

 question = gets #calculate answer puts "This is the answer" 

Then at the command prompt:

On unix:

 question.rb | answer.rb 

In the windows:

 ruby question.rb | ruby answer.rb 

Output:

 This is the question This is the answer 
+3
source share

There are two ways to do this (from my head). The easiest if you're in a Unix environment is using pipelines. A simple example:

 cat .profile .shrc | more 

This will send the output of the first command ( cat .profile .shrc ) to the more command using the pipe character | .

The second way is to call one program from another in the source code. I don't know how Ruby deals with this, but in Python you can run the program and get it using the popen function. See this chapter of the Python Learning example , then Ctrl-F for "popen" for some sample code.

+1
source share

All Articles