how to bail if stdin is empty

J

Jon Schull

I want to write a filter that will take input from files on the
command line and/or from stdin.

But if nothing has been piped to stdin, I don't want my program to
hang--I want it to do something else.

This is standard behavior for pipeable-programs I believe, but I can't
figure out how to do it...neither by reading from stdin nor by using
the fileinput module.

Thanks in advance!
 
J

Jeff Epler

You can test whether stdin is a "terminal", and act accordingly.

$ ./tt.py
Standard input is a terminal. Aborting!
$ ./tt.py < /dev/null
Standard input is a file. Doing something.

#!/usr/bin/env python

import os
if os.isatty(0):
print "Standard input is a terminal. Aborting!"
else:
print "Standard input is a file. Doing something."

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFAuzbZJd01MZaTXX0RAh/FAJ9gyjEQG3T+JpRXYTYd1C+/DsFuVwCeKAH+
JsomiFe8DWJ2YtXMKRc6Y9E=
=8zxf
-----END PGP SIGNATURE-----
 
A

Antoon Pardon

Op 2004-05-31 said:
I want to write a filter that will take input from files on the
command line and/or from stdin.

But if nothing has been piped to stdin, I don't want my program to
hang--I want it to do something else.

This is standard behavior for pipeable-programs I believe,

No it is not. Standard behaviour for filters (on unix that is)
is to use standard input if no file arguments are given.

If you start such a program without arguments and not connected
to another programs with a pipe, such a program will hang and
wait for user input from the keyboard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top