subprocess.call 彩色输出

subprocess.call output in color

有没有办法以不同的颜色显示 subprocess.call 输出,然后恢复为默认颜色?我正在使用 colorama。但以下内容对我不起作用。打印件工作正常并以绿色打印测试。

subprocess.call(["%s; " % Fore.GREEN, "hostname;" "%s" % Fore.RESET], shell=True)
subprocess.call([Fore.RED,'hostname'], shell=True)
print (Fore.GREEN,'test')

以上方法我都试过了,还是不行,

感谢您的帮助

您可以使用 subprocess.run 而不是 subprocess.call

subproces.run 有一个 capture_output 关键字可以用来实现你的目标,例如:

>>> import colorama
>>> import subprocess
>>> colorama.init(autoreset=True)
>>> out =subprocess.run(['hostname'], capture_output=True)
>>> print(colorama.Fore.GREEN + out.stdout.decode())
darknet

在这种情况下,darknet 是主机名,它可能会以绿色打印。我还设置了 autoreset=True.

更新

$ docker container run --rm -it python:3.6-alpine sh
/ # pip install colorama
Collecting colorama
  Downloading https://files.pythonhosted.org/packages/4f/a6/728666f39bfff1719fc94c481890b2106837da9318031f71a8424b662e12/colorama-0.4.1-py2.py3-none-any.whl
Installing collected packages: colorama
Successfully installed colorama-0.4.1
/ # python
Python 3.6.9 (default, Aug 21 2019, 00:27:28) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import colorama
>>> import subprocess
>>> colorama.init(autoreset=True)
>>> out = subprocess.run(['hostname'], capture_output=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/subprocess.py", line 423, in run
    with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'capture_output'
>>> process = subprocess.run(['hostname'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> print(colorama.Fore.RED + process.stdout.decode())
49e3284539b8

根据文档 https://docs.python.org/3/library/subprocess.html#subprocess.run,可以使用 stdout=subprocess.PIPE, stderr=subprocess.PIPE 实现与 capture_output 相同的行为,如上所示。