Python Command Line Arguments
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 = ''
> 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>')
> elif opt in ("-i", "--ifile"):
> inputfile = arg
> elif opt in ("-o", "--ofile"):
> outputfile = arg
> print 'In: ' + inputfile
> print 'Out: ' + outputfile
> if __name__ == "__main__":
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
# No -i option.
# Option -i present but without its required argument.
More information about the Python-list