gpt4 book ai didi

python - 使用子进程和 .Popen 自动化 .exe 程序的简单 Windows 示例

转载 作者:行者123 更新时间:2023-11-28 22:54:48 24 4
gpt4 key购买 nike

我是 subprocess 模块的新手,在阅读了 Python documents 之后在许多其他网站(包括 Stack Overflow)中,我正在努力寻找 .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,以及 stdin、stdout 和 stderr。这是我遇到问题的地方。我知道我必须使用 Popen 开始与输入 (stdin)、输出 (stdout) 和错误 (stderr) 管道通信:

from subprocess import Popen, PIPE

numcomms = Popen('numbers.exe', stdout=PIPE, stdin=PIPE, stderr=PIPE)

我不确定从这里开始做什么。使用 numcomms.stdout.read() 会导致程序停留,而使用 numcomms.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 针对输入问题提出了一个很好的解决方案,但是我在打印迭代结果时遇到了问题。

最佳答案

subprocess.stdin.write 的问题可能是您需要提供字符串而不是整数,正如 Steve Barnes 正确指出的那样。

但是,对于您的简单案例,它们可能是更简单的解决方案。 communicate 方法有一个可选的输入参数,所以这应该有效:

from subprocess import Popen, PIPE

numcomms = Popen('numbers.exe', stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = numcomms.communicate("2\n6\n")

程序的输出应该在 out 之后,并且可以使用 out.splitlines() 轻松拆分。

关于python - 使用子进程和 .Popen 自动化 .exe 程序的简单 Windows 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17642095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com