4

How could I have a program execute a target program, and then enter text into its stdin (such as raw_input.)

For example, a target program like this one:

text = raw_input("What is the text?")
if text == "a":
    print "Correct"
else:
    print "Not correct text"
PyRulez
  • 10,513
  • 10
  • 42
  • 87
user2514631
  • 187
  • 1
  • 1
  • 6

1 Answers1

2

what kind of answer are you expecting?

Yes you can. But you will also put things on stdout that wouldn't be necessary if it is used in a pipe. Furthermore, you'll have to loop over raw_input the same way you would loop over sys.stdin to get input line by line:

while True:
    text = raw_input("What is the text?")
    if text == "a":
        print "Correct"
    elif text == "stop":
        print "Bye"
        break
    else:
        print "Not correct text"

But as stated in the Zen of Python – PEP20, "There should be one-- and preferably only one --obvious way to do it." and in your case, that would be to use sys.stdin.

(Edit): as I may not have understood correctly what the OP is asking, to run another program from within a python program, you need to use subprocess.Popen()

import subprocess

text = "This is the text"

data = subprocess.Popen(['python', 'other_script.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate(input=text)
print data[0]
zmo
  • 24,463
  • 4
  • 54
  • 90
  • I think what the OP is talking about is having another program run the the original program with access to its raw_input. – PyRulez Jul 01 '13 at 13:20