1

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?

1 Answer 1

1

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' 
Sign up to request clarification or add additional context in comments.

4 Comments

I tried this. Instead of using 'print' I tried os.system('dir'). It still printed to the screen, though it got 0 into the buf. so it took this response, but didn't prevent the printing inside... :(
@OphirBack That's because os.system runs in a subshell that inherits the shell's original stdin, stdout and stderr handles, so it's unaffected by the redirection that my code performs. But you shouldn't be using os.system except for very simple stuff. Take a look at the subprocess module, which gives you control over the input and output of commands.
@OphirBack Also, seriously consider using Python 3. There's not much point developing new things in Python 2, since it will not be supported after 2020.
I wasn't sure about the subprocess thing so thanks a lot!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.