Archive for the ‘Uncategorized’ Category

Python code snippet: Read from stdin, write to file

Monday, November 9th, 2009

I was testing another script that was supposed to take the stdin and email it to me, and that script wasn’t working, so I wanted to verify that data was actually being passed into stdin in the first place so I could narrow down the problem.

Here is a really simple snippet of code which you can invoke from a command line while piping stdin into it. Example:

cat filename.txt | python thisscript.py

Here is the script itself, along with comments to explain what it’s doing.

#!/usr/local/bin/python
#
import sys
# the next line tells the script to read from stdin and use it for output
output = sys.stdin.read()
#the next line tells the script where to save the output
outfile = open('/tmp/file.txt', 'w')
#the next line tells the script to consider the file as stdout instead of the console
sys.stdout = outfile
#print the output from stdin into the file
print output
#close the file!
outfile.close()

This is useful if you are testing any application which sends email automatically using an external sendmail type application. Tell the application to use this script instead of sendmail as the email application for example, and after sending a mail from the program,

/tmp/file.txt

will contain the output of whatever the program was trying to email. It is very useful in narrowing down problems from programs which interact with external scripts via pipes. So, enjoy!