python subprocess popen同步命令 [英] python subprocess popen synchronous commands

查看:89
本文介绍了python subprocess popen同步命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 popen 来启动一个一个接一个调用两个命令(带有多个参数)的子进程.第二个命令依赖于运行的第一个命令,所以我希望使用单个子进程来运行这两个命令,而不是生成两个进程并等待第一个.

I am trying to use popen to kick off a subprocess that calls two commands (with multiple arguements) one after the other. The second command relies on the first command running, so I was hoping to use a single subprocess to run both rather than spawning two processes and wait on the first.

但是我遇到了一些问题,因为我不确定如何提供两个命令输入或将命令作为一个对象分开.

But I am running into issues because I am not sure how to give two command inputs or to seperate the command as one single object.

另外,如果可能的话,我尽量避免将 shell 设置为 true.

Also, I am trying to avoid setting shell to true if possible.

这基本上就是我想要做的:

This is essentially, what I am trying to do:

for test in resources:
    command = [
        'pgh',
        'resource',
        'create',
        '--name', test['name'],
        '--description', test['description'],
    ]
    command2 = [
        'pgh',
        'assignment',
        'create',
        '--name', test['name'],
        '--user', test['user'],
    ]


    p = Popen(command, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    print(stdout)
    print(stderr)

推荐答案

在启动另一个命令之前,您必须启动命令并等待完成.您应该对每个命令重复执行此操作.

You will have to launch command and wait for completion before launching another command. You should do this repeatedly for each command.

可以这样做

ps = [ Popen(c, stdout=PIPE, stderr=PIPE).communicate() 
       for c in command]

注意,无论第一个命令成功还是失败,这都会启动下一个命令.如果您只想在上一个命令成功时启动下一个命令,请使用

Note that this launches the next command irrespective of weather the first command succeeded or failed. If you want to launch the next command only if the previous command succeds then use

def check_execute(commands):
    return_code = 0
    for c in commands:
        p = Popen(c, stdout=PIPE, stderr=PIPE)
        result = p.communicate()
        yield result
        return_code = p.returncode
        if return_code != 0:
            break

这篇关于python subprocess popen同步命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆