How Do You Get Redirected Input?

Bengt Richter bokr at oz.net
Wed Jul 2 17:32:56 EDT 2003


On Wed, 02 Jul 2003 20:04:53 GMT, not your business <not.valid at address.org> wrote:

>Irmen de Jong wrote:
>
>> 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
>
>Okay, but there still seems to be a problem.  Lets say you typed 
>        $ mytool.py
>
>If sys.argv[1:] is empty, I want to display help.  But if I'm checking for
>redirected input by my problematic method next, the script hangs, again,
>waiting for a Enter to be pressed and the user, therefore, doesn't my usage
>help.

If you want to use empty cmd line as help trigger, I'd say don't try to read stdin
in that case. Use an explicit command line option to indicate stdin input,
e.g., just '-' (maybe where you might otherwise have a file spec).
>
>I think I need to find a way to test for redirected input without the actual
>os.read() thing.  One hack that came to mind was to fork() a seperate
>process to do this and pipe back within a time period any results. The 
>parent could just go on if no response.  But that seems a little extreme
>(and ugly) plus it's platform dependent unless, I guess, I it do it with
>threads.
>
Seems ugly. Any reason you couldn't use
     $ cat stuff | mytool.py -
or such?

BTW, on some versions of windows, that better be
     $ cat stuff | python mytool.py -
since i/o redirection with extension-associated execution has bugs for some versions (e.g. NT4).


Regards,
Bengt Richter




More information about the Python-list mailing list