snippetpythonCritical
How can I read and process (parse) command line arguments?
Viewed 0 times
parsehowlinecommandprocessreadargumentsandcan
Problem
In Python, how can we find out the command line arguments that were provided for a script, and process them?
Related background reading: What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?). For some more specific examples, see Implementing a "[command] [action] [parameter]" style command-line interfaces? and How do I format positional argument help using Python's optparse?.
Related background reading: What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?). For some more specific examples, see Implementing a "[command] [action] [parameter]" style command-line interfaces? and How do I format positional argument help using Python's optparse?.
Solution
The canonical solution in the standard library is
Here is an example:
argparse (docs):Here is an example:
from argparse import ArgumentParser
parser = 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.
Code Snippets
from argparse import ArgumentParser
parser = 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()Context
Stack Overflow Q#1009860, score: 638
Revisions (0)
No revisions yet.