2 options: sys.argv
and argparse
sys.argv
:
- Simpler, provides the command line arguments as a list of strings. So running
python helloworld.py --arg1 --arg2
will mean that sys.argv
contains
['helloworld.py', '--arg1', '--arg2']
argparse
:
- More feature rich. Unquestionably my recommendation for anything more than a singular argument.
- Supports positional and keyword arguments.
- Arguments mat have values and may be limited to presets.
- help is automatically generated
- Example:
## helloworld.py
import argparse
parser = argparse.ArgumentParser()
# Positional argument
parser.add_argument(
"operator",
help="Operator to use",
choices=("add","subtract")
)
# Optional argument with value
parser.add_argument(
"-i",
"--integer",
help="An integer",
default=0
)
# Optional argument, True if present, otherwise False
parser.add_argument(
"-sq",
"--square-everything",
action="store_true",
help="Whether all numbers will get squared"
)
args = parser.parse_args()
argument_dict = dict(args) # parse_args returns a namespace object
print(argument_dict)
python helloworld.py add -i 4 -sq
{"operator":"add", "integer":4, "square-everything": True}