I am trying to assign the output of a command to a variable without the command thinking that it is being piped. The reason for this is that the command in question gives unformatted text as output if it is being piped, but it gives color formatted text if it is being run from the terminal. I need to get this color formatted text.
So far I’ve tried a few things. I’ve tried Popen like so:
output = subprocess.Popen(command, stdout=subprocess.PIPE) output = output.communicate()[0] output = output.decode() print(output)
This will let me print the output, but it gives me the unformatted output that I get when the command is piped. That makes sense, as I’m piping it here in the Python code. But I am curious if there is a way to assign the output of this command, directly to a variable, without the command running the piped version of itself.
I have also tried the following version that relies on check_output instead:
output = subprocess.check_output(command) output = output.decode() print(output)
And again I get the same unformatted output that the command returns when the command is piped.
Is there a way to get the formatted output, the output the command would normally give from the terminal, when it is not being piped?
Advertisement
Answer
Using pexpect:
2.py:
import sys if sys.stdout.isatty(): print('hello') else: print('goodbye')
subprocess:
import subprocess p = subprocess.Popen( ['python3.4', '2.py'], stdout=subprocess.PIPE ) print(p.stdout.read()) --output:-- goodbye
pexpect:
import pexpect child = pexpect.spawn('python3.4 2.py') child.expect(pexpect.EOF) print(child.before) #Print all the output before the expectation. --output:-- hello
Here it is with grep --colour=auto
:
import subprocess p = subprocess.Popen( ['grep', '--colour=auto', 'hello', 'data.txt'], stdout=subprocess.PIPE ) print(p.stdout.read()) import pexpect child = pexpect.spawn('grep --colour=auto hello data.txt') child.expect(pexpect.EOF) print(child.before) --output:-- b'hello worldn' b'x1b[01;31mhellox1b[00m worldrn'