在子进程Popen中使用python

2024-05-18 12:04:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力使用python的子流程。我的任务是:

  1. 通过命令行启动api(这与在命令行上运行任何参数没有区别)
  2. 验证我的API是否已启动。最简单的方法就是投票选出标准。
  3. 对API运行命令。当我能够运行新命令时,将出现命令提示符
  4. 通过轮询标准输出验证命令是否完成(API不支持日志记录)

我到目前为止所做的尝试:
一。我被困在这里用波本。我明白如果我用 subprocess.call("put command here")这有效。我想尝试使用类似的东西:

import subprocess

def run_command(command):
  p = subprocess.Popen(command, shell=True,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)

在这里我使用run_command("insert command here")但这不起作用。

关于2。我认为答案应该和这里类似: Running shell command from Python and capturing the output, 但我不能得到1。为了工作,我还没试过。


Tags: 方法run命令行命令api参数标准here
2条回答

至少要真正启动子流程,必须告诉Popen对象真正通信。

def run_command(command):
    p = subprocess.Popen(command, shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
    return p.communicate()

您可以查看Pexpect,这是一个专门为与基于shell的程序交互而设计的模块。

例如,启动scp命令并等待密码提示:

child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)

关于Python 3版本,请参见Pexpect-u

相关问题 更多 >