Skip to content

Command Line Arguments

Ariel Balter edited this page Mar 31, 2016 · 5 revisions

Sys.Argv

import sys # the first argument is the name of the file args = sys.argv[1:] 

GetOpts

http://www.tutorialspoint.com/python/python_command_line_arguments.htm

getopt.getopt(args, options, [long_options])

  • args: This is the argument list to be parsed.

  • options: This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).

  • long_options: This is optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign ('='). To accept only long options, options should be an empty string.

  • This method returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped.

  • Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long options (e.g., '--long-option').

#!/usr/bin/python import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg print 'Input file is "', inputfile print 'Output file is "', outputfile if __name__ == "__main__": main(sys.argv[1:]) 

Convert the list of [opt, arg] tuples into a dictionary:

opt_dict = dict(opts) 

Yes, that simple...

https://docs.python.org/2/library/getopt.html

Argparse

https://docs.python.org/2/library/argparse.html#module-argparse

https://docs.python.org/2/howto/argparse.html

https://docs.python.org/2/howto/argparse.html

https://pymotw.com/2/argparse/

https://mkaz.tech/python-argparse-cookbook.html

https://argparse.googlecode.com/svn/trunk/doc/add_argument.html

https://argparse.googlecode.com/svn/trunk/doc/index.html

Clone this wiki locally