python子进程popen同步命令

2024-06-28 11:01:06 发布

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

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

但是我遇到了一些问题,因为我不知道如何给出两个命令输入,或者如何将命令作为一个单独的对象分开。在

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

基本上,我要做的是:

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)

Tags: nametest命令参数进程createstderrstdout
2条回答

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

可以这样做

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

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

^{2}$

根据我的理解,以下几点应该对你有用。 要在上一个完成后链接执行,请使用。在

p1 = subprocess.Popen(command, stdout=subprocess.PIPE)
p2 = subprocess.Popen(command2, stdin=p1.stdout, stdout=subprocess.PIPE)
print p2.communicate()

相关问题 更多 >