从subprocess.check\u调用接收的筛选器输出

2024-03-29 02:11:00 发布

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

需要向下面的Python3脚本添加什么特定语法,以便脚本过滤每一行结果并评估输出行是否包含特定的子字符串

下面是现在成功运行git clone命令的代码:

newpath="C:\\path\\to\\destination\\"
cloneCommand='git clone https://github.com/someuser/somerepo.git'
proc = subprocess.check_call(cloneCommand, stdout=subprocess.PIPE, shell=True, cwd=newpath, timeout=None)

上述操作成功克隆了预期回购协议。但问题是没有错误处理

我希望能够让脚本在每一行输出中侦听单词deltasdone,以便在输出中打印以下行时指示成功:

Resolving deltas: 100% (164/164), done.

subprocess.Popen(...)允许我们过滤流输出的每一行。但是,当我们运行像git clone这样的远程命令时,subprocess.Popen(...)不起作用,因为subprocess.Popen(...)不等待从像git clone这样的远程调用接收返回

What syntax do we need to use to filter the output from calls to subprocess.check_call(...)?


Tags: togit命令脚本远程deltasclonecheck
1条回答
网友
1楼 · 发布于 2024-03-29 02:11:00

我们可以执行一个小脚本来测试Popen代码。它在使用我们选择的代码退出之前生成一些STDOUT和STDERR,可以选择延迟:

from sys import stdout, stderr, exit, argv
from time import sleep

stdout.write('OUT 1\nOUT 2\nOUT 3\n')
sleep(2)
stderr.write('err 1\nerr 2\n')
exit(int(argv[1]))

演示如何使用Popen的脚本。此脚本的参数将是我们要执行的外部命令

import sys
from subprocess import Popen, PIPE

# A function that takes some subprocess command arguments (list, tuple,
# or string), runs that command, and returns a dict containing STDOUT,
# STDERR, PID, and exit code. Error handling is left to the caller.
def run_subprocess(cmd_args, shell = False):
    p = Popen(cmd_args, stdout = PIPE, stderr = PIPE, shell = shell)
    stdout, stderr = p.communicate()
    return dict(
        stdout = stdout.decode('utf-8').split('\n'),
        stderr = stderr.decode('utf-8').split('\n'),
        pid = p.pid,
        exit_code = p.returncode,
    )

# Run a command.    
cmd = sys.argv[1:]
d = run_subprocess(cmd)

# Inspect the returned dict.
for k, v in d.items():
    print('\n#', k)
    print(v)

如果第一个脚本名为other_program.py,而这个脚本名为demo.py,那么您可以沿着以下几行运行整个过程:

python demo.py python other_program.py 0  # Exit with success.
python demo.py python other_program.py 1  # Exit with failure.
python demo.py python other_program.py X  # Exit with a Python error.

注释中与OP讨论的git clone用法示例:

$ python demo.py git clone  progress  verbose https://github.com/hindman/jump

# stdout
['']

# stderr
["Cloning into 'jump'...", 'POST git-upload-pack (165 bytes)', 'remote: Enumerating objects: 70, done.        ', 'remote: Total 70 (delta 0), reused 0 (delta 0), pack-reused 70        ', '']

# pid
7094

# exit_code
0

相关问题 更多 >