How To Use Stdout In Python

In this tutorial, we will learn how to use stdout in Python to redirect and display text output from a running Python script.

Redirecting and displaying output using stdout is an important skill when you’re working with files or reading data that is generated by other programs.

Step 1: Understanding What is Stdout in Python

Stdout, or standard output, is a file-like object that represents the output stream in Python. The sys.stdout object is where the print() function sends its output by default, usually to the console or terminal.

It is part of Python’s sys module, which provides access to some variables and functions used or maintained by the interpreter.

In other words, when you use the print() function in Python, the text string is sent to sys.stdout. By default, this is set to the console or terminal, but it can be redirected to another file or stream.

Step 2: Redirecting Stdout to a File

To redirect stdout to a file, you can simply reassign sys.stdout to the desired file object. Let’s write a simple example to see how this works:

In this example, we first save the current value of sys.stdout to a variable called original_stdout. Then, we create a new file object called file and reassign sys.stdout to it. Now, when we call the print() function, the output will be written to the file instead of the terminal. After we’re done printing to the file, we restore the original stdout.

Step 3: Printing to Stdout

To print to stdout after redirecting it, you can simply call the print() function:

As we have seen in the previous example, if you have redirected stdout to a file before this line, the output will go to the file. After restoring the original stdout, the output will be displayed in the console or terminal as initially intended.

Step 4: Restoring Stdout

As mentioned earlier, after redirecting stdout to a file, you might want to restore the original stdout to print to the console or terminal again. You can do this by reassigning sys.stdout to the variable where the original stdout was stored:

Now, any calls to print() after this line will output text to the console or terminal.

Full example code:

Output:

This text will be printed to stdout.

And your “output.txt” file will contain:

This text will be written to the file.

Conclusion

Redirecting and using stdout in Python is an essential skill to work with output streams and manage where your program sends its output data. In this tutorial, we have learned the basics of using stdout in Python, how to redirect stdout to a file, how to print to stdout, and how to restore the original stdout. With this knowledge, you can now redirect and display output in any way that fits your needs.