在子进程 Popen 中使用 python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14438845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using python with subprocess Popen
提问by strangenewstar
I am struggling to use subprocesses with python. Here is my task:
我正在努力将子进程与 python 一起使用。这是我的任务:
- Start an api via the command line (this should be no different than running any argument on the command line)
- Verify my API has come up. The easiest way to do this would be to poll the standard out.
- Run a command against the API. A command prompt appears when I am able to run a new command
- Verify the command completes via polling the standard out (the API does not support logging)
- 通过命令行启动 api(这应该与在命令行上运行任何参数没有什么不同)
- 验证我的 API 已经出现。最简单的方法是轮询标准。
- 针对 API 运行命令。当我能够运行新命令时会出现命令提示符
- 通过轮询标准输出来验证命令是否完成(API 不支持日志记录)
What I've attempted thus far:
1. I am stuck here using the Popen. I understand that if I use
subprocess.call("put command here")this works. I wanted to try to use something similar to:
到目前为止我尝试过的:
1. 我被困在这里使用 Popen。我明白,如果我使用
subprocess.call("put command here")这个作品。我想尝试使用类似的东西:
import subprocess
def run_command(command):
p = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
where I use run_command("insert command here")but this does nothing.
我在哪里使用,run_command("insert command here")但这没有任何作用。
with respect to 2. I think the answer should be similar to here: Running shell command from Python and capturing the output, but as I can't get 1. to work, I haven't tried that yet.
关于 2. 我认为答案应该类似于这里: 从 Python 运行 shell 命令并捕获输出,但由于我无法使 1. 工作,所以我还没有尝试过。
采纳答案by Thorsten Kranz
To at least really start the subprocess, you have to tell the Popen-object to really communicate.
至少要真正启动子进程,您必须告诉 Popen 对象真正进行通信。
def run_command(command):
p = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return p.communicate()
回答by CharlesB
You can look into Pexpect, a module specifically designed for interacting with shell-based programs.
您可以查看Pexpect,这是一个专为与基于 shell 的程序交互而设计的模块。
For example launching a scp command and waiting for password prompt you do:
例如,启动 scp 命令并等待密码提示,您可以:
child = pexpect.spawn('scp foo [email protected]:.')
child.expect ('Password:')
child.sendline (mypassword)
See Pexpect-ufor a Python 3 version.
有关Python 3 版本,请参阅Pexpect-u。

