如何拦截输出到Windows 10 cmd.exe并修改添加颜色?

问题描述 投票:0回答:1

我正在从命令行调用另一个程序来创建visual studio解决方案并构建它们。该程序输出这些命令的结果。我想打印以黄色文本输出的警告线,而不是默认的灰色和错误线以红色输出。

我们假设我的cmd.exe控制台已被修改为支持将ascii2转义代码渲染为颜色输出。

我已经做了很多寻找解决方案,但我发现的大部分内容都是为linux / osx做的。我找到了一个给出正则表达式作为输入的脚本,可以使用指定的规则替换文本。 regex script

我是否可以在后台运行此脚本,但仍然连接到cmd.exe,以便它将在输出到cmd.exe的所有文本上运行,以运行正则表达式搜索并在文本之前替换是否显示在cmd.exe窗口中?我可以把它放到批处理文件或python脚本中。

我想布置特定的应用程序,但为了使这个问题更具通用性,我如何将现有的脚本/程序应用于后台运行的cmd.exe提示符,这样用户仍然可以在cmd提示符下运行命令,但后台程序是否适用于用户运行的命令?

如果没有其他高效的解决方案存在,我愿意尝试使用PowerShell。

用于检测行是否为错误的正则表达式仅搜索单词错误

"\berror\b"

这是一个警告的搜索

"\bwarning\b"
python windows batch-file cmd
1个回答
0
投票

编辑:首先添加更好的解决方案。此解决方案设置管道,以便它可以从外部程序接收输出,然后实时打印彩色结果。

#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)
© www.soinside.com 2019 - 2024. All rights reserved.