Domanda

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"
È stato utile?

Soluzione

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]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top