简体   繁体   中英

How to check if fileinput is empty? Python

I have created a Python program which runs from command line, the user inputs files for processing. The files are read in from fileinput, and optparse options can be used on them. My problem is that if the user does not input any option or file name, the program does nothing and continues running. I want the program to display the help options by default if fileinput is empty.

Is there a way to check to see if fileinput.input(argv) is empty? It defaults to stdin when empty , but how can I check if it is empty beforehand?

def parse_options():
    parser = optparse.OptionParser()
    parser.add_option('-o', '--output', dest='output',
                      default='c',
                      help='[c/f/h] output to (c)onsole, (f)ile or (h)tml')
    parser.add_option('-s', '--sort', dest='sort',
                      default='pa',
                      help='[p/c/m/d] sort by (p)ath, (c)all frequency, (m)ean duration or (d)uration,\n'
                           '[a/d] sort by (a)scending or (d)escending order')

    options, argv = parser.parse_args()

    if options.output == 'f':
        output_action = LogAnalyser.output_to_file
    elif options.output == 'h':
        output_action = LogAnalyser.output_to_html
    else:
        output_action = LogAnalyser.output_to_console

    #if fileinput.input(argv) is None:
    #    parser.print_help()
    #    quit()

    return output_action, options.sort, fileinput.input(argv)

Well, if optparse parser returns a positional argument list, you can simply check it for emptiness:

(options, args) = parser.parse_args()
...
if args:
    for line in fileinput.input(args):
        ...

If this isn't enough, please elaborate your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM