0

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)
0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I want the user to be able to use the program just by entering file names as well, so they may not always use an options argument. Sorry I did not make this clear.
Where do you want to enter file names?
At command line, I would like it to be python scriptname.py file1.txt file2.txt with possible options like -o f
This is as exactly it will be after optparse processing. Do you really call it?
Okay, I understand you now, sorry about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.