[英]Using python with subprocess Popen
I am struggling to use subprocesses with python. 我正在努力将子进程与python一起使用。 Here is my task: 这是我的任务:
What I've attempted thus far: 到目前为止,我尝试过的是:
1. I am stuck here using the Popen. 1.我使用Popen卡在这里。 I understand that if I use subprocess.call("put command here")
this works. 我知道,如果我使用subprocess.call("put command here")
可以正常工作。 I wanted to try to use something similar to: 我想尝试使用类似于以下内容的内容:
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.正常工作,所以我还没有尝试过。
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()
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 myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)
See Pexpect-u for a Python 3 version. 有关Python 3版本,请参见Pexpect-u 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.