如何在Python中检查两个管道子进程中的一个是否失败?

2024-07-01 07:33:01 发布

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

以这段代码为例(tar可以用-z-J-J压缩,我知道有一个tarfile特定的模块,但它代表了一个长时间运行的进程)

    from subprocess import Popen, PIPE
    with open('tarball.tar.gz', 'w+') as tarball:
        tarcmd = Popen(['tar', '-cvf', '-', '/home'], stdout=PIPE)
        zipcmd = Popen(['gzip', '-c'], stdin=tarcmd.stdout, stdout=tarball)
        tarcmd.stdout.close()
        zipcmd.communicate()
        # added a while loop that breaks when tarcmd gets a
        # proper return value. Can it be considerate a good
        # solution?
        while tarcmd.poll() is None:
            print('waiting...')

        # test the values and do stuff accordingly

这是在python子进程中管道化两个命令的典型示例。现在检查zipcmd的返回码很容易,但是如何检查tarcmd是否失败?如果我检查它的返回码,我总是一个也得不到(我想是因为stdout关闭了)。基本上,如果两个命令中的一个失败,我想引发一个异常。在bash中有$PIPESTATUS,如何在python中实现?在


Tags: 模块代码from命令进程stdout代表tar
1条回答
网友
1楼 · 发布于 2024-07-01 07:33:01

if i check its returncode i always get none

如果值是None,则表示相应的子进程仍然是活动的。顺便说一句,不需要在循环中调用tarcmd.poll()。您可以使用tarcmd.wait()阻止它直到它退出。在

模拟shell管道不容易出错:

#!/usr/bin/env python
from subprocess import check_call

check_call('set -e -o pipefail; tar -cvf - /home | gzip -c > tarball.tar.gz', 
           shell=True, executable='/bin/bash')

通过颠倒进程初始化顺序:

^{pr2}$

使用shell=True(如果命令是从源文件中的字符串文本等可信输入构造的)或使用库(如^{})来运行管道,而不是直接在Popen上实现它,可能会更容易。在

#!/usr/bin/env python
from plumbum.cmd import gzip, tar

(tar['-cvf', '-', '/home'] | gzip['-c'] > 'tarball.tar.gz')()

How do I use subprocess.Popen to connect multiple processes by pipes?

相关问题 更多 >

    热门问题