用Popen获取输出彩色文本

2024-06-07 08:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我用popen做了一个插件,这个插件用一个外部程序在输出中显示一些彩色文本。在

输出如下:

avr-g++ -o .pioenvs\uno\FrameworkArduino\HardwareSerial.o -c -std=gnu++11 -fno-exceptions -fno-threadsafe-statics -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO_ARCH_AVR -DARDUINO_AVR_UNO -DARDUINO=10607 -I.pioenvs\uno\FrameworkArduino -I.pioenvs\uno\FrameworkArduinoVariant .pioenvs\uno\FrameworkArduino\HardwareSerial.cpp    
avr-g++ -o .pioenvs\uno\FrameworkArduino\HardwareSerial0.o -c -std=gnu++11 -fno-exceptions -fno-threadsafe-statics -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO_ARCH_AVR -DARDUINO_AVR_UNO -DARDUINO=10607 -I.pioenvs\uno\FrameworkArduino -I.pioenvs\uno\FrameworkArduinoVariant .pioenvs\uno\FrameworkArduino\HardwareSerial0.cpp
=============================================
Path\file.cpp: in function 'void loop()':
Path\file.cpp:23:2 error: expected ';' before '}' token
}
^
=============================================

“=”内有红色和黄色。在

当我在命令控制台中运行命令时,我可以看到完整的输出,但是当我使用Popen时,我只能得到未着色的文本

我就是这样用波本的

^{pr2}$

我想得到的文本,即使它不是彩色的,重要的是得到完整的日志。在

如有任何建议,我们将不胜感激


Tags: gnu文本插件cpp彩色unostdavr
2条回答

When I run the command in the command console, I can see the full output, but when I use Popen I only can get the uncolored text

可能存在两个问题:

  1. 彩色文本恰好是在stderr上生成的,而不是stdout。要捕获stderr,请设置stderr=PIPEas @Rahman suggested

  2. avr-g++命令检测到输出不是tty时可能禁用颜色,例如,如果它被重定向到与您的情况类似的管道。要启用颜色,请传递命令行选项-fdiagnostics-color=alwaysas @PM 2Ring suggested。在

    或者提供一个伪tty来蒙蔽avr-g++命令,使其认为它是以交互方式运行的(因此它应该启用颜色)。您可以使用^{}, ^{} module

    import pexpect # $ pip install pexpect
    
    output, exitstatus = pexpect.runu(command, withexitstatus=1)
    

    或者(更低级的)使用^{} + ^{} module

您无法获得所有这些消息,因为命令输出的一部分不是常规输出,它被视为错误(或日志或调试消息)

现在您可以将stderr=subprocess.PIPE添加到Popen的参数中,这将把stderr变量中的所有错误:

process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cwd, universal_newlines=True, shell=True)
output = process.communicate()

stdout = output[0]
stderr = output[1]

print(stdout)
print(stderr)

或者,如果您希望所有的错误和输出与您在控制台中看到的一样,请在命令末尾添加2>&1。比如:

^{pr2}$

相关问题 更多 >

    热门问题