The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Python module: argparse - How to parse arguments using Python script on the command line - video tutorials
By Guest on 8th November 2022 12:58:58 AM | Syntax: PYTHON | Views: 178



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1.  
  2. The "argparse" module's support for command-line interfaces is built
  3. around an instance of "argparse.ArgumentParser".  It is a container
  4. for argument specifications and has options that apply the parser as
  5. whole:
  6.  
  7.   parser = argparse.ArgumentParser(
  8.                       prog = 'ProgramName',
  9.                       description = 'What the program does',
  10.                       epilog = 'Text at the bottom of help')
  11.  
  12. The "ArgumentParser.add_argument()" method attaches individual
  13. argument specifications to the parser.  It supports positional
  14. arguments, options that accept values, and on/off flags:
  15.  
  16.   parser.add_argument('filename')           # positional argument
  17.   parser.add_argument('-c', '--count')      # option that takes a value
  18.   parser.add_argument('-v', '--verbose',
  19.                       action='store_true')  # on/off flag
  20.  
  21. The "ArgumentParser.parse_args()" method runs the parser and places
  22. the extracted data in a "argparse.Namespace" object:
  23.  
  24.   args = parser.parse_args()
  25.   print(args.filename, args.count, args.verbose)
  26.  
  27.  
  28. Example
  29. =======
  30.  
  31. The following code is a Python program that takes a list of integers
  32. and produces either the sum or the max:
  33.  
  34.   import argparse
  35.  
  36.   parser = argparse.ArgumentParser(description='Process some integers.')
  37.   parser.add_argument('integers', metavar='N', type=int, nargs='+',
  38.                       help='an integer for the accumulator')
  39.   parser.add_argument('--sum', dest='accumulate', action='store_const',
  40.                       const=sum, default=max,
  41.                       help='sum the integers (default: find the max)')
  42.  
  43.   args = parser.parse_args()
  44.   print(args.accumulate(args.integers))
  45.  
  46. Assuming the above Python code is saved into a file called "prog.py",
  47. it can be run at the command line and it provides useful help
  48. messages:
  49.  
  50.   $ python prog.py -h
  51.   usage: prog.py [-h] [--sum] N [N ...]
  52.  
  53.   Process some integers.
  54.  
  55.   positional arguments:
  56.    N           an integer for the accumulator
  57.  
  58.   options:
  59.    -h, --help  show this help message and exit
  60.    --sum       sum the integers (default: find the max)
  61.  
  62. When run with the appropriate arguments, it prints either the sum or
  63. the max of the command-line integers:
  64.  
  65.   $ python prog.py 1 2 3 4
  66.   4
  67.  
  68.   $ python prog.py 1 2 3 4 --sum
  69.   10
  70.  
  71. If invalid arguments are passed in, an error will be displayed:
  72.  
  73.   $ python prog.py a b c
  74.   usage: prog.py [-h] [--sum] N [N ...]
  75.   prog.py: error: argument N: invalid int value: 'a'
  76.  
  77. The following sections walk you through this example.
  78.  
  79.  
  80. Creating a parser
  81. -----------------
  82.  
  83. The first step in using the "argparse" is creating an "ArgumentParser"
  84. object:
  85.  
  86.   >>> parser = argparse.ArgumentParser(description='Process some integers.')
  87.  
  88. The "ArgumentParser" object will hold all the information necessary to
  89. parse the command line into Python data types.
  90.  
  91.  
  92. Adding arguments
  93. ----------------
  94.  
  95. Filling an "ArgumentParser" with information about program arguments
  96. is done by making calls to the "add_argument()" method. Generally,
  97. these calls tell the "ArgumentParser" how to take the strings on the
  98. command line and turn them into objects.  This information is stored
  99. and used when "parse_args()" is called. For example:
  100.  
  101.   >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
  102.   ...                     help='an integer for the accumulator')
  103.   >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
  104.   ...                     const=sum, default=max,
  105.   ...                     help='sum the integers (default: find the max)')
  106.  
  107. Later, calling "parse_args()" will return an object with two
  108. attributes, "integers" and "accumulate".  The "integers" attribute
  109. will be a list of one or more integers, and the "accumulate" attribute
  110. will be either the "sum()" function, if "--sum" was specified at the
  111. command line, or the "max()" function if it was not.
  112.  
  113.  
  114. Parsing arguments
  115. -----------------
  116.  
  117. "ArgumentParser" parses arguments through the "parse_args()" method.
  118. This will inspect the command line, convert each argument to the
  119. appropriate type and then invoke the appropriate action. In most
  120. cases, this means a simple "Namespace" object will be built up from
  121. attributes parsed out of the command line:
  122.  
  123.   >>> parser.parse_args(['--sum', '7', '-1', '42'])
  124.   Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
  125.  
  126. In a script, "parse_args()" will typically be called with no
  127. arguments, and the "ArgumentParser" will automatically determine the
  128. command-line arguments from "sys.argv".
  129.  
  130.  
  131. ArgumentParser objects
  132. ======================
  133.  
  134. class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)
  135.  
  136.   Create a new "ArgumentParser" object. All parameters should be
  137.   passed as keyword arguments. Each parameter has its own more
  138.   detailed description below, but in short they are:
  139.  
  140.   * prog - The name of the program (default:
  141.     "os.path.basename(sys.argv[0])")
  142.  
  143.   * usage - The string describing the program usage (default:
  144.     generated from arguments added to parser)
  145.  
  146.   * description - Text to display before the argument help (by
  147.     default, no text)
  148.  
  149.   * epilog - Text to display after the argument help (by default, no
  150.     text)
  151.  
  152.   * parents - A list of "ArgumentParser" objects whose arguments
  153.     should also be included
  154.  
  155.   * formatter_class - A class for customizing the help output
  156.  
  157.   * prefix_chars - The set of characters that prefix optional
  158.     arguments (default: '-')
  159.  
  160.   * fromfile_prefix_chars - The set of characters that prefix files
  161.     from which additional arguments should be read (default: "None")
  162.  
  163.   * argument_default - The global default value for arguments
  164.     (default: "None")
  165.  
  166.   * conflict_handler - The strategy for resolving conflicting
  167.     optionals (usually unnecessary)
  168.  
  169.   * add_help - Add a "-h/--help" option to the parser (default:
  170.     "True")
  171.  
  172.   * allow_abbrev - Allows long options to be abbreviated if the
  173.     abbreviation is unambiguous. (default: "True")
  174.  
  175.   * exit_on_error - Determines whether or not ArgumentParser exits
  176.     with error info when an error occurs. (default: "True")
  177.  
  178.   Changed in version 3.5: *allow_abbrev* parameter was added.
  179.  
  180.   Changed in version 3.8: In previous versions, *allow_abbrev* also
  181.   disabled grouping of short flags such as "-vv" to mean "-v -v".
  182.  
  183.   Changed in version 3.9: *exit_on_error* parameter was added.
  184.  
  185. The following sections describe how each of these are used.
  186.  
  187.  
  188. prog
  189. ----
  190.  
  191. By default, "ArgumentParser" objects use "sys.argv[0]" to determine
  192. how to display the name of the program in help messages.  This default
  193. is almost always desirable because it will make the help messages
  194. match how the program was invoked on the command line.  For example,
  195. consider a file named "myprogram.py" with the following code:
  196.  
  197.   import argparse
  198.   parser = argparse.ArgumentParser()
  199.   parser.add_argument('--foo', help='foo help')
  200.   args = parser.parse_args()
  201.  
  202. The help for this program will display "myprogram.py" as the program
  203. name (regardless of where the program was invoked from):
  204.  
  205.   $ python myprogram.py --help
  206.   usage: myprogram.py [-h] [--foo FOO]
  207.  
  208.   options:
  209.    -h, --help  show this help message and exit
  210.    --foo FOO   foo help
  211.   $ cd ..
  212.   $ python subdir/myprogram.py --help
  213.   usage: myprogram.py [-h] [--foo FOO]
  214.  
  215.   options:
  216.    -h, --help  show this help message and exit
  217.    --foo FOO   foo help
  218.  
  219. To change this default behavior, another value can be supplied using
  220. the "prog=" argument to "ArgumentParser":
  221.  
  222.   >>> parser = argparse.ArgumentParser(prog='myprogram')
  223.   >>> parser.print_help()
  224.   usage: myprogram [-h]
  225.  
  226.   options:
  227.    -h, --help  show this help message and exit
  228.  
  229. Note that the program name, whether determined from "sys.argv[0]" or
  230. from the "prog=" argument, is available to help messages using the
  231. "%(prog)s" format specifier.
  232.  
  233.   >>> parser = argparse.ArgumentParser(prog='myprogram')
  234.   >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
  235.   >>> parser.print_help()
  236.   usage: myprogram [-h] [--foo FOO]
  237.  
  238.   options:
  239.    -h, --help  show this help message and exit
  240.    --foo FOO   foo of the myprogram program
  241.  
  242.  
  243. usage
  244. -----
  245.  
  246. By default, "ArgumentParser" calculates the usage message from the
  247. arguments it contains:
  248.  
  249.   >>> parser = argparse.ArgumentParser(prog='PROG')
  250.   >>> parser.add_argument('--foo', nargs='?', help='foo help')
  251.   >>> parser.add_argument('bar', nargs='+', help='bar help')
  252.   >>> parser.print_help()
  253.   usage: PROG [-h] [--foo [FOO]] bar [bar ...]
  254.  
  255.   positional arguments:
  256.    bar          bar help
  257.  
  258.   options:
  259.    -h, --help   show this help message and exit
  260.    --foo [FOO]  foo help
  261.  
  262. The default message can be overridden with the "usage=" keyword
  263. argument:
  264.  
  265.   >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
  266.   >>> parser.add_argument('--foo', nargs='?', help='foo help')
  267.   >>> parser.add_argument('bar', nargs='+', help='bar help')
  268.   >>> parser.print_help()
  269.   usage: PROG [options]
  270.  
  271.   positional arguments:
  272.    bar          bar help
  273.  
  274.   options:
  275.    -h, --help   show this help message and exit
  276.    --foo [FOO]  foo help
  277.  
  278. The "%(prog)s" format specifier is available to fill in the program
  279. name in your usage messages.
  280.  
  281. Video tutorials:
  282. Argparse Basics - How I run my scripts via the Command Line




  283.  
  284. Python argparse tutorial (beginner - intermediate)




  285.  
  286. Understanding Python: Argparse CLI
  287.  
  288. [inline]
















Python software and documentation are licensed under the PSF License Agreement.
Starting with Python 3.8.6, examples, recipes, and other code in the documentation are dual licensed under the PSF License Agreement and the Zero-Clause BSD license.
Some software incorporated into Python is under different licenses. The licenses are listed with code falling under that license. See Licenses and Acknowledgements for Incorporated Software for an incomplete list of these licenses.

Python and it's documentation is:
Copyright © 2001-2022 Python Software Foundation. All rights reserved.
Copyright © 2000 BeOpen.com. All rights reserved.
Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

See History and License for complete license and permissions information:
https://docs.python.org/3/license.html#psf-license
  • Recent Pastes