How do I avoid processing an empty stdin with python?

非 Y 不嫁゛ 提交于 2019-12-05 19:05:36

grep can work the way it does because it has one non-optional argument: the pattern. For example

$ grep < /dev/zero
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.

even though there was infinite input available on stdin, grep didn't get the required argument and therefore complained.

If you want to use only optional arguments and error out if stdin is a terminal, look at file.isatty().

import sys,os
print os.fstat(sys.stdin.fileno()).st_size > 0

Calling script

c:\py_exp>peek_stdin.py < peek_stdin.py
True

c:\py_exp>peek_stdin.py
False

You may want to check getopt module. Basic example:

import getopt
import sys

def main(argv):
    try:
        opts, args = getopt.getopt(argv, "has:f:") # "has:f:" are the arguments 
    except getopt.GetoptError:
        print "print usage()"
        sys.exit(1)
    if not opts and not args:
        print "print usage()"
        sys.exit(1)

    print "args passed", opts, args
if __name__ == "__main__":
    main(sys.argv[1:])


~> python blabla.py
print usage()
~> python blabla.py -a arg
args passed [('-a', '')] ['arg']
~> python blabla.py -b as  ----> this fails because -b is not defined for getopt at second parameter
print usage()

What about this one:

#!/usr/bin/env python
import getopt
import sys
import select


def main(argv):
    try:
        opts, args = getopt.getopt(argv, "has:f:") # "has:f:" are the arguments
    except getopt.GetoptError:
        print "print usage()"
        sys.exit(1)
    if not opts and not args:
        a, b, c = select.select([sys.stdin], [], [], 0.2)
        if a:
            itera = iter(a[0].readline, "")
            for line in itera:
                data = line.strip()
                print data
        else:
            print "print usage()"

    print "args passed", opts, args
if __name__ == "__main__":
    main(sys.argv[1:])

select.select helps to check if there is data coming

:~> ./hebele.py 
print usage()
args passed [] []

:~> ping www.google.com | ./hebele.py 
PING www.google.com (173.194.67.105) 56(84) bytes of data.
64 bytes from blabla (173.194.67.105): icmp_seq=1 ttl=48 time=16.7 ms
64 bytes from blabla (173.194.67.105): icmp_seq=2 ttl=48 time=17.1 ms
64 bytes from blabla (173.194.67.105): icmp_seq=3 ttl=48 time=17.1 ms
^CTraceback (most recent call last):
  File "./hebele.py", line 25, in <module>
    main(sys.argv[1:])
  File "./hebele.py", line 17, in main
    for line in itera:
KeyboardInterrupt
:~> ls | ./hebele.py 
Aptana_Studio_3
Desktop
...
workspace
args passed [] []

:~> ./hebele.py -a bla
args passed [('-a', '')] ['bla']
:~> ./hebele.py sdfsdf sadf sdf
args passed [] ['sdfsdf', 'sadf', 'sdf']
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!