This is a follow up question from here specifically concerning its answer.
From a python module I am calling a Hello World executable that simply prints Hello World
to the stdout. I am interested in redirecting that output to a python StringIO
and ran into this answer which almost brings me all the way to the solution.
The critical part of this answer is this code segment:
1. def redirect_stdout():
2. print "Redirecting stdout"
3. sys.stdout.flush() # <--- important when redirecting to files
4. newstdout = os.dup(1)
5. devnull = os.open('/dev/null', os.O_WRONLY)
6. os.dup2(devnull, 1)
7. os.close(devnull)
8. sys.stdout = os.fdopen(newstdout, 'w')
Also I would like to restore the stdout as it was before the redirection.
Questions
- What exactly is going on in the function above?
- What is
dup
anddup2
doing? - What is
/dev/null
? - What is line 8 doing? (
sys.stdout = os.fdopen(newstdout, 'w')
)
- What is
- How can I store the stdout in a
StringIO
object? - How can I restore the stdout after the call to my Hello World program?
I am pretty sure that once I have the answer for my question 1 that the answers of questions 2 and 3 will be easy. I decided to post them anyway to maybe push the answer of question 1 into the direction where I want to go.
redirect_stdout
. How would I restore the stdout again so that external programs can print to stdout?os.dup2(1, devnull)
does not seem to be working?! – Copaiba