我有一个3d方python脚本,它从命令行接受输入。从这个脚本(input.py)相关的代码如下所示:如何在两个python脚本之间进行通信?
import sys
def chooseinput():
valid_inputs = ('a', 'b')
inp = raw_input('Enter choice (%s): ' % "/".join(valid_inputs))
if inp not in valid_inputs:
sys.stderr.write("Unsupported input %s\n" % inp)
return
print 'You chose ' + '\'' + inp + '\''
return inp
if __name__ == "__main__":
chooseinput()
# do something with the input...
chooseinput()
# do something with the input...
我想写另一个python脚本(harness.py)来生成以上脚本的输入。
import subprocess
def harness():
p = subprocess.Popen(['python', 'input.py'], stdin=subprocess.PIPE)
p.stdin.write('a')
p.stdin.write('b')
if __name__ == '__main__':
harness()
在命令行中,我跑:
$ python harness.py
Enter choice (a/b): Enter choice (a/b): Traceback (most recent call last):
File "input.py", line 13, in <module>
chooseinput()
File "input.py", line 5, in chooseinput
inp = raw_input('Enter choice (%s): ' % "/".join(valid_inputs))
EOFError: EOF when reading a line
如果我只在第一个脚本一个输入,然后我就可以通过移除第二写入调用使第二个脚本工作。如果第一个脚本需要多个输入,那么我会得到上述错误。
谢谢,这看起来非常方便。 – Ravi 2011-05-24 00:15:04