我怎样才能让程序执行目标程序,然后将文本输入到它的标准输入(例如 raw_input。)
例如,像这样的目标程序:
text = raw_input("What is the text?")
if text == "a":
print "Correct"
else:
print "Not correct text"
最佳答案
你期待什么样的答案?
是的,你可以。但是你也会把一些东西放在 stdout 上,如果它在管道中使用就不需要了。此外,您必须像遍历 sys.stdin
一样遍历 raw_input
以逐行获取输入:
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"
但如 Zen of Python – PEP20 中所述,“应该有一个——最好只有一个——显而易见的方法来做到这一点。”在你的情况下,那就是使用sys.stdin
。
(编辑):因为我可能没有正确理解 OP 的要求,要从 python 程序中运行另一个程序,您需要使用 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]
关于python - 在 Python 中通过管道传输到 raw_input(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17394477/