将 stdout 传输到下一个 Popen stdin 时捕获 subprocess.Popen 的错误

问题描述 投票:0回答:0

我正在尝试“链接”多个 Popen 子进程,并捕获每个命令引发的任何错误。 我正在使用 Python 3.7。

这是我尝试使用的一些代码的示例:

import subprocess
from subprocess import Popen, PIPE, CalledProcessError

try:
    process_breakmulti = Popen(['vcfbreakmulti', vcf_file], stdout=PIPE, stderr=PIPE, encoding='utf-8')
    (out, err) = process_breakmulti.communicate()
    if process_breakmulti.returncode != 0:
        print(err, process_breakmulti.stderr)
except CalledProcessError as e:
    print(e.output)

#use the stdout of process_breakmulti as stdin for process_allelicprimitives

try:
    process_allelicprimitives = Popen(['vcfallelicprimitives', '-kg'], stdin=process_breakmulti.stdout, stdout=PIPE, stderr=PIPE, encoding='utf-8')
    (out, err) = process_allelicprimitives.communicate()
    if process_allelicprimitives.returncode != 0:
        print(err, process_allelicprimitives.stderr)
except CalledProcessError as e:
    print(e.output)

这是上面代码抛出的错误。

....
    process_allelicprimitives = Popen(['vcfallelicprimitives', '-kg'], stdin=process_breakmulti.stdout, stdout=PIPE, stderr=PIPE, encoding='utf-8')
  File "/hpc-home/ethering/anaconda3/envs/python37/lib/python3.7/subprocess.py", line 753, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/hpc-home/ethering/anaconda3/envs/python37/lib/python3.7/subprocess.py", line 1376, in _get_handles
    p2cread = stdin.fileno()
ValueError: I/O operation on closed file

我认为我没有正确使用communicate()方法,但不确定如何正确使用。

如果有人能告诉我如何正确使用它,我真的很感激。

subprocess pipe popen communicate
© www.soinside.com 2019 - 2024. All rights reserved.