简体   繁体   English

在子进程Popen中使用python

[英]Using python with subprocess Popen

I am struggling to use subprocesses with python. 我正在努力将子进程与python一起使用。 Here is my task: 这是我的任务:

  1. Start an api via the command line (this should be no different than running any argument on the command line) 通过命令行启动api(这与在命令行上运行任何参数没有什么不同)
  2. Verify my API has come up. 验证我的API是否已启动。 The easiest way to do this would be to poll the standard out. 最简单的方法是轮询标准。
  3. Run a command against the API. 针对API运行命令。 A command prompt appears when I am able to run a new command 当我能够运行新命令时出现命令提示符
  4. Verify the command completes via polling the standard out (the API does not support logging) 通过轮询标准输出来验证命令是否完成(API不支持日志记录)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM