How to read/process command line arguments? How to read/process command line arguments? python python

How to read/process command line arguments?

import sysprint("\n".join(sys.argv))

sys.argv is a list that contains all the arguments passed to the script on the command line. sys.argv[0] is the script name.


import sysprint(sys.argv[1:])

The canonical solution in the standard library is argparse (docs):

Here is an example:

from argparse import ArgumentParserparser = ArgumentParser()parser.add_argument("-f", "--file", dest="filename",                    help="write report to FILE", metavar="FILE")parser.add_argument("-q", "--quiet",                    action="store_false", dest="verbose", default=True,                    help="don't print status messages to stdout")args = parser.parse_args()

argparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.

Just going around evangelizing for argparse which is better for these reasons.. essentially:

(copied from the link)

  • argparse module can handle positionaland optional arguments, whileoptparse can handle only optionalarguments

  • argparse isn’t dogmatic aboutwhat your command line interfaceshould look like - options like -fileor /file are supported, as arerequired options. Optparse refuses tosupport these features, preferringpurity over practicality

  • argparse produces moreinformative usage messages, includingcommand-line usage determined fromyour arguments, and help messages forboth positional and optionalarguments. The optparse modulerequires you to write your own usagestring, and has no way to displayhelp for positional arguments.

  • argparse supports action thatconsume a variable number ofcommand-line args, while optparserequires that the exact number ofarguments (e.g. 1, 2, or 3) be knownin advance

  • argparse supports parsers thatdispatch to sub-commands, whileoptparse requires settingallow_interspersed_args and doing theparser dispatch manually

And my personal favorite:

  • argparse allows the type andaction parameters to add_argument()to be specified with simplecallables, while optparse requireshacking class attributes likeSTORE_ACTIONS or CHECK_METHODS to getproper argument checking