14

I have the following simple Python code.

stdout = sys.stdout
stderr = sys.stderr

try:
   # Omitted

finally:
  sys.stdout = stdout

After searching, I found that sys.stdin, sys.stdout, and sys.stderr are file objects corresponding to the interpreter's standard input, standard output and standard error streams. So, my guess here is that we first assign the sys.stdout and sys.stderr to the variables stdout and stderr.

Then, even if there are exceptions in the try statement, can we always get the sys.stdout back? Is this correct? I felt that I was still confused.

1
  • 3
    No matter what happened in what case? It's not clear what you're asking or trying to accomplish Commented Jul 15, 2015 at 2:08

2 Answers 2

35

In normal C programs, there are three "files" open by default: stdin, stdout, and stderr. When you do input and output in C, by default they come from stdin and stdout. But, you can also use them where code expects files, or reassign them to be new files.

Python seeks to "mimic" this behavior of C. When you print() in Python, your text is written to Python's sys.stdout. When you do input(), it comes from sys.stdin. Exceptions are written to sys.stderr.

You can reassign these variables in order to redirect the output of your code to a file other than stdout. This is very similar to shell redirection, if you're familiar with that. The reason you might do something like this is to keep a log of your program's output or make code "shut up", i.e. not send output to stdout. So, in your example example:

stdout = sys.stdout

try:
    sys.stdout = open('file.txt', 'w')
    print('blah')
    # etc
finally:
    sys.stdout.close()  # close file.txt
    sys.stdout = stdout
    sys.stderr = stderr

This code wouldn't print anything to the console, but it would write "blah" to a text file named file.txt. To make this sort of thing less error-prone, Python provides sys.__stdin__ and sys.__stdout__, which always hold the original values of sys.stdin and sys.stdout. The above code could be made simpler using this:

try:
    sys.stdout = open('file.txt', 'w')
    print('blah')
    # etc
finally:
    sys.stdout.close()  # close file.txt
    sys.stdout = sys.__stdout__

The reason Python has both stdout and __stdout__ is mainly for convenience, so you don't have to make a variable to back up stdout.

However, I have to recommend that you don't make a habit out of reassigning stdout. It's pretty easy to mess things up that way! If you want to save your code's output, you can use shell redirection. If you want to have the ability to keep a log of what your program is doing, see Python's logging module. If you want your code to be quieter, give your functions a quiet=False parameter so you can shut them up when you want! There is rarely a "genuine" need to do reassign stdout, etc. Python allows you to do it, because Python gives programmers a lot of control, and expects them to be responsible. You could do something like this, if you really wanted to:

>>> import random
>>> random.random = lambda: 1
>>> random.random()
1
>>> random.random()
1
Sign up to request clarification or add additional context in comments.

3 Comments

So, what is the difference between 'sys.stdin' and 'sys._stdin' in python ?
I updated the answer a lot with more information. I accidentally gave you bad info... it's __stdout__, not _stdout! Also, the difference is really that print() uses stdout, and __stdout__ is there as a backup in case you "lose" the original value.
Help me understand when things are written to the screen. You say " Exceptions are written to sys.stderr.". BUT, when my code crashes it always prints to the terminal...does that mean that displaying to the terminal come from the union of content from sys.err AND sys.stdout?
0

About the link you sent for the logging module, it seems to be deprecated (which is almost guaranteed after more than 8 years). Here should (hopefully) be the right link for the logging module.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.