使用Popen获取输出彩色文本

GEP*_*EPD 6 python popen python-2.7 output

我正在使用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
}
^
=============================================
Run Code Online (Sandbox Code Playgroud)

所有内部"="都是红色和黄色.

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

这就是我使用Popen的方式

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

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

print(stdout)
print(stderr)
Run Code Online (Sandbox Code Playgroud)

我想获得文本,即使它没有着色,重要的是获得完整的日志.

任何建议将不胜感激

Rah*_*man 4

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

现在您可以添加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)
Run Code Online (Sandbox Code Playgroud)

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

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 2>&1
Run Code Online (Sandbox Code Playgroud)

  • @GEPD这是我在回答你之前阅读的链接http://stackoverflow.com/a/818284/811922 (3认同)
  • @GEPD:要了解如何保留颜色代码,请查看 [avr-g++ 手册页](https://manned.org/avr-g++) 中的 `-fdiagnostics-color[=WHEN]`。 (3认同)