How to read/process command line arguments?
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments.
What are some of the ways Python programmers can do this?
Related
- What’s the best way to grab/parse command line arguments passed to a Python script?
- Implementing a “[command] [action] [parameter]” style command-line interfaces?
- How can I process command line arguments in Python?
- How do I format positional argument help using Python’s optparse?
import sys
print("\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.
Basically,
import sys
print(sys.argv[1:])
The canonical solution in the standard library is 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.