我正在尝试编写一个与 bsdgames trek 程序交互的 Python 程序。这有点像 Zork with Klingons:
* * * S T A R T R E K * * *
Press return to continue.
What length game: short
What skill game: fair
Enter a password: hunter2
10 Klingons
2 starbases at 3,6, 0,2
It takes 400 units to kill a Klingon
Command:
我目前正在尝试使用subprocess.Popen()
它与之交互:
>>> import subprocess
>>> t = subprocess.Popen('trek', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
很遗憾:
>>> t.communicate('')
('', None)
>>> t.poll()
-2
>>> t.communicate('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 754, in communicate
return self._communicate(input)
File "/usr/lib/python2.7/subprocess.py", line 1297, in _communicate
self.stdin.flush()
ValueError: I/O operation on closed file
一旦我.communicate()
使用它,它就会自行结束。它似乎回应了我的第一个.communicate()
:
>>> t = subprocess.Popen('trek', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> t.communicate('\n')
('\n * * * S T A R T R E K * * *\n\nPress return to continue.\nWhat length game: ', None)
但我需要能够读取标准输出才能弄清楚下一个标准输入应该是什么。那么,如何在不告诉 trek 输入结束的情况下将内容发送到 stdin 呢?
编辑:有人建议t.stdin.write()
。这可行,但现在我找不到读取结果的方法:
>>> t.stdin.write('\n')
>>> t.poll()
>>> t.stdout.read()
这永远挂起:
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyboardInterrupt
>>> t.stdout.readline()
''
那么现在发生了什么?