将答案传递给 popen.subprocess
pass answers to popen.subprocess
有没有办法轻松地将答案传递给 python 中的可执行文件?
我有一个 shell 安装脚本(第三方),它会在安装前询问一些参数。我想从我的 python 脚本中提供该参数。
有可能吗?
像
subprocess.popen(myscript,["answer1","answer2"])
有一个很棒的 Python 模块可以做到这一点,叫做 pexpect
下面是一个使用它以交互方式 运行 scp 的示例(来自 pexpect 文档):
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:') # wait for 'Password:' to show up
child.sendline (mypassword)
Is something possible ? like subprocess.popen(myscript,["answer1","answer2"])
是的。如果您知道所有答案,那么您可以使用 Popen.communicate()
传递答案:
#!/usr/bin/env python
from subprocess import Popen, PIPE
process = Popen(myscript, stdin=PIPE, universal_newlines=True)
process.communicate("\n".join(["answer1", "answer2"]))
在某些情况下可能会失败,您可以使用 pexpect
模块(如 ), to workaround possible block-buffering issues or issues when input/output is outside of standard streams. See Q: Why not just use a pipe (popen())?
有没有办法轻松地将答案传递给 python 中的可执行文件?
我有一个 shell 安装脚本(第三方),它会在安装前询问一些参数。我想从我的 python 脚本中提供该参数。
有可能吗? 像 subprocess.popen(myscript,["answer1","answer2"])
有一个很棒的 Python 模块可以做到这一点,叫做 pexpect
下面是一个使用它以交互方式 运行 scp 的示例(来自 pexpect 文档):
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:') # wait for 'Password:' to show up
child.sendline (mypassword)
Is something possible ? like
subprocess.popen(myscript,["answer1","answer2"])
是的。如果您知道所有答案,那么您可以使用 Popen.communicate()
传递答案:
#!/usr/bin/env python
from subprocess import Popen, PIPE
process = Popen(myscript, stdin=PIPE, universal_newlines=True)
process.communicate("\n".join(["answer1", "answer2"]))
在某些情况下可能会失败,您可以使用 pexpect
模块(如