python - 使用 Popen 获取输出彩色文本

标签 python python-2.7 output popen

我正在使用 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 时,我只能得到未着色的文本

这就是我使用 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)

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

任何建议将不胜感激

最佳答案

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

现在您可以将 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。像这样的东西:

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

关于python - 使用 Popen 获取输出彩色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34624751/

相关文章:

python - re模块中的groups和groups有什么区别?

python - 仅从 BeautifulSoup 获取数字而不是整个 div

python-2.7 - 嵌入Mayavi时在vtkOutputWindow中禁用或捕获VTK警告

python - 是否可以从python中的函数返回两个列表

python - 无法在 Python 上安装 iPy

c++ - 仅将类的一个方法移植到 C?

python - Python请求库遇到重试限制时如何访问服务器响应

python - 打印超出其精度的 float

javascript - 将输入选择作为文本输出到元素

c - EOF 在 c 中无法正常工作,打印也很荒谬