使用pexpect:
2.py:
import sys
if sys.stdout.isatty():
print('hello')
else:
print('goodbye')
子:
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
这里是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 world\n'
b'\x1b[01;31mhello\x1b[00m world\r\n'