Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I take the output of one program and use it as the input of another?

Tags:

python

io

ruby

I've looked at this and it wasn't much help.

I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?

Thanks for your help.

EDIT
Thanks to the guys that mentioned piping. I haven't used it too much and was glad it was brought up since it forced me too look in to it more.

like image 937
Nope Avatar asked Jan 21 '09 14:01

Nope


1 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 2 lines could be made into one:

print p.communicate(answer)[0]
like image 88
nosklo Avatar answered Sep 21 '22 19:09

nosklo