我有一个用 Python 实现的自定义 Git 命令,它使用subprocess
模块中的方法来调用git
。我注意到,根据所使用的方法,输出可能会或可能不会有颜色,例如:
import subprocess
subprocess.run('git push origin --delete foobar', shell=True)
print()
print(subprocess.run('git push origin --delete foobar', shell=True,
capture_output=True, encoding='utf-8').stderr, end='')
输出:
如何保留捕获的输出(stdout 和 stderr)中的颜色?
许多命令会检测它们是否未将输出发送到“终端”,如果没有,则不会添加特定于终端的代码来显示颜色。当您缺少颜色时就会出现这种情况。 一些git 命令(不确定所有命令)可以接受–color参数 - 请查看手册页。