将运行时参数传递给 python 中的子进程

Passing runtime arguments to the subprocess in python

我有一个名为 app.exe 的程序,它接受 1 个参数并开始 execution.While app.exe 正在执行,它会提示我进行确认,例如 --"Are you sure you want to continue?"I不得不说yes/no.

现在我在 python 中编写了一个程序,它将与 app.exe 对话,提供 1 个输入 parameter.But 我无法为 app.exe 提供 [=19] =] 选项(对于 Are you sure you want to continue?) via my script.Below is my program.

proc=Popen(outlines, shell=True, stdin=PIPE, stdout=PIPE)
#Outlines is the command which contains 1 input parameter.
proc.communicate(input='n\n')[0]
#I saw this in python documentation.But it is not working.

让我知道我在这里缺少什么。

proc = Popen(outlines, shell=True, stdin=PIPE, stdout=PIPE)
stdOut = ''
answered = False
while proc.Poll() is None:
    stdOut += proc.stdout.read()
    if answered is False and 'sure you want to continue' in stdOut:
        proc.stdin.write('n\n')
        proc.stdin.flush()
        answered = True # Not the most beautiful way to solve it, but chuck it.. it works.
proc.stdout.close()

一如既往,有人会对此发表评论,所以我会继续说下去。

  1. 如果你 PIPE stdout 或 stderr,你需要从缓冲区中读取,否则它可能会满,这将意外挂起你的应用程序。在这种情况下,您无论如何都需要检查 "are you sure..." 的输出,这样它就会自行解决,但请记住这一点。

  2. 另一件需要注意的事情是,出于多种原因,使用 shell=True 是不好的 and/or 危险的。我从来没有遇到过问题,但这是每个人都喜欢抛出的事实,我相信总有一天会有人向我和你解释。或者,如果您有兴趣,也可以 google。

  3. 如果您使用 while proc.Poll() == None: 如果函数 return 和 0 可能会出现问题,因此使用 is 进行比较确保以正确的状态退出循环。

  4. 不要忘记关闭你的 proc.stdout,如果你调试你的应用程序并且你在短时间内开始许多会话,将没有足够的文件句柄来打开另一个 stdout(因为出于各种原因它算作文件句柄)。

由于 .read() 如果没有要读取的数据显然会挂起应用程序,您将不得不轮询对象并询问是否有要获取的输入。 如果您使用 Linux,则可以使用 select 执行此操作,而在 Windows 上,您可以使用排序线程来检查和报告数据。

暂时让你继续前进的小气鬼版本是在你用 \n 回答后忽略 stdout,即使实际上不推荐这样做。

proc = Popen(outlines, shell=True, stdin=PIPE, stdout=PIPE)
stdOut = ''
answered = False
while proc.Poll() is None:
    if not answered: # This makes all the difference
        stdOut += proc.stdout.read()
    if answered is False and 'sure you want to continue' in stdOut:
        proc.stdin.write('n\n')
        proc.stdin.flush()
        answered = True

再一次,我不会纵容这一点 运行。但它可能会让您了解为什么会发生这种情况,并让您继续推进您的项目,这样您就不会在一个细节上停留太久。