Reputation: 167
I'm currently building a shell in python. The shell can execute python files, but I also need to add the option to use PIPEs (for example '|' means that the output of the first command will be the input of the second command).
In order to do so, I need to have the option to take what the first command was going to print (notice that the command might not be a system command but a python file that has the line
print 'some information'
I need to pass it on to a variable in the shell. Can anyone help?
Upvotes: 1
Views: 88
Reputation: 55469
You can redirect sys.stdout
to an in-memory BytesIO
or StringIO
file-like object:
import sys
from io import BytesIO
buf = BytesIO()
sys.stdout = buf
# Capture some output to the buffer
print 'some information'
print 'more information'
# Restore original stdout
sys.stdout = sys.__stdout__
# Display buffer contents
print 'buffer contains:', repr(buf.getvalue())
buf.close()
output
buffer contains: 'some information\nmore information\n'
Upvotes: 1