Python Command Line Arguments

MRAB python at mrabarnett.plus.com
Wed Apr 12 22:38:24 EDT 2017


On 2017-04-13 02:59, ian.stegner at gmail.com wrote:
> I have this code which I got from https://www.tutorialspoint.com/python/python_command_line_arguments.htm The example works fine but when I modify it to what I need, it only half works. The problem is the try/except. If you don't specify an input/output, they are blank at the end but it shouldn't be.
> 
> 
> import getopt
> import sys
> 
> def main(argv):
>     inputfile = ''
>     outputfile = ''
>     try:
>        opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
>     except getopt.GetoptError:
>        inputfile = 'Input'
>        outputfile = 'Output'
>     if inputfile == '':
>        for opt, arg in opts:
>           if opt == '-h':
>              print ('Usage: Encrypt.py -i <input file> -o <output file>')
>              sys.exit()
>           elif opt in ("-i", "--ifile"):
>              inputfile = arg
>           elif opt in ("-o", "--ofile"):
>              outputfile = arg
>     else:
>        ''
> 
>     print 'In: ' + inputfile
>     print 'Out: ' + outputfile
> 
> if __name__ == "__main__":
>     main(sys.argv[1:])
> 
You'll get the GetoptError exception if an option that requires an 
argument doesn't have one. That's not the same as omitting the option 
entirely.

For example:

     # No -i option.
     foo

     # Option -i present but without its required argument.
     foo -i


More information about the Python-list mailing list