How Do You Get Redirected Input?

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Wed Jul 2 15:34:16 EDT 2003


not your business wrote:
> I have a shell tool that accepts arguments on the command line. I would like
> to check if the input is being piped in.  That is,
>  
>         $ mytool.py < cmdlst.txt
> 
> In this case sys.argv is empty. So I added
> 
>         pipein = os.read(sys.stdin.fileno(),256)
>         if (pipein):
>             input_args = pipein.split()
>         else:
>             input_args = sys.argv[1:]
>  
> Problem is that if nothing is redirected in, the script waits for a Enter
> pressed on the the keyboard. Anyone know a solution to this?  Thanx in
> advance for any help.

Why not turn it around? First check if sys.argv is *not* empty,
in which case the user provided command line arguments, and
proceed to parse those. Otherwise (if sys.argv *is* empty),
assume the input is piped in and proceed to read the standard
input.

--Irmen





More information about the Python-list mailing list