简体   繁体   中英

how show error if no args was set in console trying execute python script

I need to write python script which need command arguments for executing. I have such code:

try:
    opts, args = getopt.getopt(argv,"htt:tf:d:",["from=","to=","on="])
except getopt.GetoptError:
    print 'logReader.py -f <from> -t <to> -d <on>'
    sys.exit(2)
for opt, arg in opts:
    if opt == '-h':
        print 'logReader.py -f <from> -t <to> -d <on>'
        sys.exit()
    # elif opt
    elif opt in ("-f", "--from"):
        fromTime = arg
    elif opt in ("-t", "--to"):
        toTime = arg
    elif opt in ("-d", "--on"):
        onDate = arg  

But than I run my script without any arguments it just do nothing. How can I add some check like if no args are specified the error message should be shown in the console (or help)

With no arguments set, opts will be an empty list:

if not opts:
    print 'logReader.py -f <from> -t <to> -d <on>'
    sys.exit(2)

You should really consider using the argparse module instead, which lets you specify that some command line options are mandatory.

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