未捕获Python子进程“git gc”stderr

这是我观察到的行为:

>>> out = subprocess.check_output("git gc", shell=True)
Counting objects: 4869, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (1219/1219), done.
Writing objects: 100% (4869/4869), done.
Total 4869 (delta 3607), reused 4869 (delta 3607)

操作输出在STDERR中打印.我想在变量中捕获这个,所以我将stderr发送到STDOUT.但它没有抓住它.

>>> out = subprocess.check_output("git gc", shell=True, stderr=subprocess.STDOUT)
>>> out
b''
>>> print(out)
b''

有什么想法/建议吗?

似乎git gc是一种特殊情况,其中输出重定向是不可能的.在另一个问题中建议使用打字稿,但是有更多知识的人可以解释这种行为吗?脚本方法不起作用,因为它没有退出fork.

最佳答案 git gc真的是一个特例,请看这里:

Trying to redirect ‘git gc’ output

尝试使用git status来查看差异.

更新

问题是一个很好的挑战.一位同事查看了GIT的源代码,发现如果进程没有在后台启动,git gc只会写入stdout.经过一番搜索,我遇到了pty library,并受到了https://stackoverflow.com/a/6953572/2776376的启发,找到了一个有效的解决方案.下面的代码捕获了git gc的stdout,尽管它必须写入文件.

#!/usr/bin/env python

import os
import pty
import sys

log_name = 'git_log.txt'

def git_logger():
    (child_pid, fd) = pty.fork()
    if child_pid == 0:
        #parent process
        sys.stdout.flush()
        os.execlp("git", "git", "gc")
    else:
        #child process
        output = os.read(fd, 100)
        while True:
            try:
                output += os.read(fd, 1024)
            except:
                break
        with open(log_name, 'w') as log_file:
            log_file.write(output)

if __name__ == "__main__":
    git_logger()
    with open(log_name, 'r') as log_file:
        print(log_file.read())
点赞