def main():
import sys
print sys.stdin.read()
if __name__ == '__main__':
main()
$ echo "fred" | python script.py
fred
$
I think if you want to replicate stdin behaviour try looking into
the xargs command, assuming that is available on your platform.
However reading in stdin into argv may be more elegant, but slightly
unexpected to the experienced user.
Dennis O.
You can check
if os.isatty(sys.stdin): # <-- this check
do_stuff_with_the_terminal()
else:
read_options_from_stdin()
-tkc
You may want to just use the appropriate shell syntax instead:
$ python myscript `echo fred`
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
Here is what I came up with:
The one weird thing, the line from above didn't seem to work so I changed it
if os.isatty(sys.stdin):
to this:
if not os.isatty(sys.stdin.fileno()):
Below 3 tests, with stdin redirection, then with one argument, then
with both stdin redirection and one argument, the results are at the
very bottom.
$ cat ./argvtest.py; echo "fred" | ./argvtest.py ; ./argvtest.py
"alice"; echo "fred" | ./argvtest.py "bob"
#!/usr/bin/python
import os
import sys
def main():
#This checks to see if stdin is a not tty and > 0
if not os.isatty(sys.stdin.fileno()):
arg = sys.stdin.read()
print arg
elif len(sys.argv[1:]) > 0:
# if the length of the first argument is > 0
#[1:] strip the first string beacause it is the name of the script
arg = sys.argv[1:]
print arg
if __name__ == "__main__":
main()
fred
['alice']
fred
>
> Thanks,
>
> Mark
>
Welcome,
Dennis O.
> fred
>
> ['alice']
> fred
Just realized the if/else will have to be changed slightly if we want
to output both argv and stdin.
Any reason for that over sys.stdin.isatty()?
my knowledge of os.isatty() existing and my previous lack of
knowledge about sys.stdin.isatty()
:)
-tkc
$ cat script.py
def main():
print raw_input()
if __name__ == '__main__':
main()
$ echo "fred" | python script.py
fred
$
Hope this helps,
-- HansM