[英]Filter output received from subprocess.check_call
需要在下面的 Python 3 腳本中添加什么特定語法,以便腳本過濾每一行結果並評估 output 的任何行是否包含特定子字符串?
這是現在成功運行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)
以上成功克隆了預期的回購。 但問題是沒有錯誤處理。
我希望能夠讓腳本監聽單詞deltas
並在 output 的每一行中done
,以便在 output 中打印以下行時它可以指示成功:
Resolving deltas: 100% (164/164), done.
subprocess.Popen(...)
允許我們過濾流 output 的每一行。 但是,當我們運行git clone
類的遠程命令時, subprocess.Popen(... subprocess.Popen(...)
不起作用,因為 subprocess.Popen subprocess.Popen(...)
不會等待接收來自遠程調用(如git clone
)的返回。
我們需要使用什么語法來過濾來自對 subprocess.check_call
subprocess.check_call(...)
的調用的 output ?
我們可以執行一個小腳本來測試我們的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
的腳本。 該腳本的 arguments 將是我們要執行的外部命令。
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.
git clone
的用法示例與評論中的 OP 討論:
$ 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.