How Do You Get Redirected Input?
not your business
not.valid at address.org
Wed Jul 2 16:04:53 EDT 2003
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.
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.
More information about the Python-list
mailing list