Using stdin, stdout, and stderr in Python
Standard input (stdin), output (stdout) and error (stderr) data are associated with command line executions within shells like the command prompt in Windows or bash in Linux. The standards can be used within a Python script by first importing the sys
module. Let’s pretend our command line has the form1:
$ [input] | python script.py > out.log 2> err.log
In this example, the string |
is the pipe operator directing the input to Python, > out.log
directs Python’s stdout (the output of the script) to the file out.log
, and 2> err.log
directs Python’s stderr to the file err.log
.
We can use these pipeline tools in our own Python script, like this:
import sys
for line in sys.stdin:
# Process stdin
print("[stdout output]") # Print statements go to stdout
print("[stderr output]", file=sys.stderr) # (Python Ver. 3) print to stderr instead of stdout
print >> sys.stderr, "[stderr output]" # (Python Ver. 2) print to stderr instead of stdout
For example, let’s say we have a text file
import sys
for line in sys.stdin:
print(line + "to stdout")
print(line + "to sterr", file=sys.stderr)
Open up your shell (terminal), and enter this line:
$ cat testInput.txt | python script.py > out.log 2> err.log
Note: If you’re using the Windows command prompt, replace cat
with type
.
Once you run this code, a file called
Standard Input to stdout
and
Standard Input to sterr
The cat
command normally prints the contents of your file to your terminal. By using stdin, we pass cat
command output to a Python script, send the output of our Python script (which would normally be printed to the screen) to a file, and send custom error messages to the stderr for our own custom error logging.
If you try to execute the above
File "script.py", line 4 print(line + "to sterr", file=sys.stderr) ^ SyntaxError: invalid syntax
Hopefully this helped you figure out the differences between stdin, stdout, and stderr and how you can use them to enhance your Python program. If you found it helpful, subscribe below for more free Python lessons, then share this tutorial on Facebook and Twitter.
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
-
Here we are using the standard notation that “$” indicates an input line to a shell, and that the character itself is not used. ↩