这是我观察到的行为:
>>> 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是一种特殊情况,输出重定向是不可能的。在另一个问题中建议使用 typescript ,但是有更多知识的人可以解释这种行为吗?脚本方法不起作用,因为它没有退出 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())
关于未捕获 Python 子进程 "git gc"stderr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36918411/