使用python将enterKey传递给exe文件

2024-09-24 22:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在python脚本中运行一个外部exe文件。我需要两件事。在

  1. 获取exe输出到stdout(stderr)的任何内容。在
  2. 只有在我按enter键之后,exe才会停止执行。我无法改变这种行为。我需要脚本在获得上一步的输出后传递enter键输入。在

这就是我目前为止所做的,我不知道该怎么做。在

import subprocess

first = subprocess.Popen(["myexe.exe"],shell=True,stdout=subprocess.PIPE)

Tags: 文件import脚本true内容stderrstdoutshell
1条回答
网友
1楼 · 发布于 2024-09-24 22:24:28
from subprocess import Popen, PIPE, STDOUT
first = Popen(['myexe.exe'], stdout=PIPE, stderr=STDOUT, stdin=PIPE) 
while first.poll() is None:
    data = first.stdout.read()
    if b'press enter to' in data:
        first.stdin.write(b'\n')
first.stdin.close()
first.stdout.close()

这个管道stdin同样,不要忘记关闭打开的文件句柄(stdin和stdout在某种意义上也是文件句柄)。在

还要避免shell=True如果可能的话,我经常自己使用它,但是best practices say you shouldn't。在

这里我假设python3,stdin和{}假设字节数据作为输入和输出。在

first.poll()将轮询exe的退出代码,如果没有给定,则表示它仍在运行。在

其他一些提示

一件乏味的事是把论点传给波本,一件简单的事是:

^{pr2}$

它保留空格分隔的输入,并在其周围加引号,例如python myscript.py debug "pass this parameter somewhere"将导致来自sys.argv的三个参数,['myscript.py', 'debug', 'pass this parameter somewhere']-在将来使用Popen时可能会有用

另一个好的方法是在读取stdout之前检查它是否有输出,否则它可能会挂起应用程序。为此,您可以使用select
或者,您可以使用pexpect,这通常与SSH一起使用,因为它位于应用程序之外的另一个用户空间中,当它请求输入时,您需要手动分叉exe并使用os.read()从特定的pid中读取,或者使用pexpect。在

相关问题 更多 >