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
2> err.log directs Python’s stderr to the file
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
Once you run this code, a file called
Standard Input to stdout
Standard Input to sterr
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.
Want to do more with Python?
We've uncovered a lot more tricks to help you get the most out of Python. To take your Python programming to the next level, enter your email address below and we'll send you our most powerful Python tricks yet.
Here we are using the standard notation that “$” indicates an input line to a shell, and that the character itself is not used. ↩