我是 subprocess 模块的新手,在阅读了许多其他网站(包括 Stack Overflow)中的Python 文档.Popen
后,我很难找到、.communicate
和其他此类有用类的简化示例。通常,这些示例从不连续使用每个类,只是单独使用。此外,许多示例都是基于 Linux 的,例如 的使用["ls", "-l"]
,这使得 Windows 用户很难理解。
在玩了这个模块几个小时后,我遇到了几个问题,最好通过一个简单的.exe命令行程序打开和通信的方法来说明。
例如,假设程序名为“numbers.exe”,它会询问以下问题:
>>> Question 1) Choose 1, 2 or 3
>>> Question 2) Choose 4, 5 or 6
>>> You have answered #(Q1) and #(Q2)
>>> *Use these values in an iterative sequence displaying each stage in the iteration*
然后我想自动操作这个程序,即我希望 python 输入 2 和 6 而无需我做任何事情,但仍然打印问题。然后我希望能够在 python 中查看迭代。
这里的第一个考虑是我可以使用:
from subprocess import Popen, PIPE
numprog = subprocess.call('numbers.exe')
print(numprog.communicate())
但是,这只是打开程序,我仍然需要自己输入 2 和 6。为了自动化这个过程,我相信我必须使用Popen
标准输入、标准输出和标准错误。这是我遇到问题的地方。我知道我必须使用 Popen 开始与输入 (stdin)、输出 (stdout) 和错误 (stderr) 管道进行通信:
from subprocess import Popen, PIPE
numcomms = Popen('numbers.exe', stdout=PIPE, stdin=PIPE, stderr=PIPE)
我不确定从这里做什么。usingnumcomms.stdout.read()
会导致程序停留,而 usingnumcomms.stdin.write(2)
会抛出 int 值无法使用的错误。该numprog.communicate
课程似乎要求您自己输入值。
据我所见,伪代码如下:
>>> Open numbers.exe stdin, stdout and stderr pipes using Popen
>>> Print first question using stdout
>>> Enter "2" using stdin
>>> Print second question using stdout
>>> Enter "6" using stdin
>>> Receive a string saying "You have answered 2 and 6" using stdout
>>> Display the results of each stage of the iteration using stdout
我该怎么写这个?
非常感谢您的帮助,谢谢!
编辑:编辑问题以描述迭代序列问题。Michael 提出了一个很好的解决输入问题的方法,但是我在打印迭代结果时遇到了麻烦。