![](/img/trans.png)
[英]How to manipulate cmd.exe from python, so that the output is shown in the cmd.exe window
[英]How to intercept output to windows 10 cmd.exe and modify to add color?
我正在从命令行调用另一个程序来创建Visual Studio解决方案并进行构建。 该程序输出这些命令的结果。 我想打印以黄色文本输出的警告行,而不是以红色显示默认的灰色和错误行。
假设我的cmd.exe控制台已被修改为支持将ascii2转义码呈现为彩色输出。
我已经做了很多寻找解决方案的工作,但是我发现的大多数东西都是针对linux / osx制作的。 我确实找到了一个以正则表达式作为输入的脚本,可以使用指定的规则替换文本。 正则表达式脚本
我是否可以在后台运行此脚本,但仍连接到cmd.exe,这样它将在输出到cmd.exe的所有文本上运行,以运行正则表达式搜索并在文本之前替换显示在cmd.exe窗口中? 我可以将其放入批处理文件或python脚本中。
我想布局特定的应用程序,但要使这个问题可能更笼统,我如何将现有的脚本/程序应用到后台正在运行的cmd.exe提示符下,以便用户仍可以在cmd提示符下运行命令,但是后台程序是否适用于用户运行的命令?
如果没有其他可行的可行解决方案,我愿意尝试使用powershell。
检测行是否为错误的正则表达式仅搜索单词error
"\berror\b"
搜索警告的方法相同
"\bwarning\b"
编辑:首先添加更好的解决方案。 该解决方案设置了Pipe,以便它可以接收来自外部程序的输出,然后实时打印着色结果。
#Python 2
from subprocess import Popen, PIPE
def invoke(command):
process = Popen(command, stdout=PIPE, bufsize=1)
with process.stdout:
#b'' is byte. Per various other SO posts, we use this method to
#iterate to workaround bugs in Python 2
for line in iter(process.stdout.readline, b''):
line = line.rstrip()
if not line:
continue
line = line.decode()
if "error" in line:
print (bcolors.FAIL + line + bcolors.ENDC)
elif "warning" in line:
print (bcolors.WARNING + line + bcolors.ENDC)
else:
print (line)
error_code = process.wait()
return error_code
为此,我将build命令的输出插入到文件中。 然后,我编写了这个python脚本来安装所需的依赖项,循环遍历文件内容,然后使用适当的颜色打印数据。
现在,我将研究一种实时对输出进行着色的解决方案,因为该解决方案要求用户在看到着色的输出之前等待构建完成。
#Python 2
import pip
def install(package):
if hasattr(pip, 'main'):
pip.main(['install', package])
else:
pip._internal.main(['install', package])
class bcolors:
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def print_text():
install('colorama')
try:
import colorama
colorama.init()
except:
print ("could not import colorama")
if len(sys.argv) != 2:
print ("usage: python pretty_print \"file_name\"")
return 0
else:
file_name = sys.argv[1]
with open(sys.argv[1], "r") as readfile:
for line in readfile:
line = line.rstrip()
if not line:
continue
if "error" in line:
print (bcolors.FAIL + line + bcolors.ENDC)
elif "warning" in line:
print (bcolors.WARNING + line + bcolors.ENDC)
else:
print (line)
return 0
if __name__ == "__main__":
ret = print_text()
sys.exit(ret)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.