使用Popen获取输出彩色文本

时间:2016-01-06 02:41:12

标签: 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)

即使文字没有上色,我也希望得到文字,重要的是获得完整的日志。

任何建议都将受到赞赏

2 个答案:

答案 0 :(得分: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)

或者,如果您想要在控制台中看到所有错误和输出,请在命令末尾添加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

答案 1 :(得分:2)

  

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

可能有两个问题:

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

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

    或者(不太便携但可以使用更多命令)提供伪tty来欺骗avr-g++命令,使其认为它以交互方式运行(因此它应该启用颜色)。你可以使用pty.spawn(), pexpect module

    来做到这一点
    import pexpect # $ pip install pexpect
    
    output, exitstatus = pexpect.runu(command, withexitstatus=1)
    

    或(更低级别)使用pty.openpty() + subprocess module

相关问题