【问题标题】:How to make python script press 'enter' when prompted on ShellShell提示时如何使python脚本按“输入”
【发布时间】:2015-10-10 16:52:07
【问题描述】:

我想自动升级程序。

我在 Python 中运行这段代码:

import subprocess
subprocess.call('./upgrade')

当我这样做时,我从 shell 中获得升级过程成功启动的输出,然后我得到“按 Enter 继续”。我将如何自动化这个过程,以便 python 脚本在提示时自动“按下”输入?我需要在手术过程中这样做两次。 我需要在 Linux 而不是 Windows 上完成此操作,正如这里所要求的: Generate keyboard events 此外,这需要在 Shell 提示 Enter 后专门完成。 谢谢你的帮助。 我在这里没有找到解决方案: Press enter as command input

【问题讨论】:

标签: python linux


【解决方案1】:

您可以使用subprocess.Popensubprocess.communicate 将输入发送到另一个程序。

例如,向以下程序test_enter.py发送“回车”键:

print "press enter..."
raw_input()
print "yay!"

您可以执行以下操作:

from subprocess import Popen, PIPE
p = Popen(['python test_enter.py'], stdin=PIPE, shell=True)
p.communicate(input='\n')

您可能会发现"how do i write to a python subprocess' stdin" 的答案也很有帮助。

【讨论】:

  • 引用子进程模块(python 3)关于inputif self.universal_newlines is True, this should be a string; if it is False, "input" should be bytes。所以:input=b'\n'
  • 为我自己和其他可能遇到此问题的人发表评论。当我使用Popen 而不是call 时,communicate API 将被阻塞或超时,然后根据官方文档,它说:注意如果要向进程的标准输入发送数据,则需要在我的代码中添加这个之后,使用stdin=PIPE 创建 Popen 对象,它可以工作。
猜你喜欢
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
相关资源
最近更新 更多