First of all, if you have some arguments that can be omitted, those arguments ought to be options and not real arguments.
Python provides more than one way to parse arguments. The best choice is argparse
, which has tons of features and its the module where the development is continuing. If you have to support "old" versions of python then you might be interested in optparse
, even though it's been deprecated in python3.2. There exist also a getopt
module which mimics C's getopt(do not use this! It's there more for historical reasons and to help people used with these old style of parsing)
A simple example using argparse
might be:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--option-name', action='store', dest='option_name_var')
parser.add_argument('numbers', type=int, nargs='*')
parsed = parser.parse_args() #parses sys.argv by default
print(parsed.numbers)
print(parsed.option_name_var)
Which can be used as:
$python example.py 1 2 3
[1, 2, 3]
None
$python example.py 1 2 3 --option-name "value"
[1, 2, 3]
value
$python example.py 1 2 3 --option-name
usage: example.py [-h] [--option-name OPTION_NAME_VAR] [numbers [numbers ...]]
example.py: error: argument --option-name: expected one argument
$python example.py --option-name
usage: example.py [-h] [--option-name OPTION_NAME_VAR] [numbers [numbers ...]]
example.py: error: argument --option-name: expected one argument
$python example.py --option-name 5
[]
5
$python example.py 1 2 "string"
usage: example.py [-h] [--option-name OPTION_NAME_VAR] [numbers [numbers ...]]
example.py: error: argument numbers: invalid int value: 'string'
Note how the numbers are automatically converted to a list of integers, and an error is issued if the value is not an integer or there are missing arguments etc.
You also have a default help text:
$python example.py -h
usage: example.py [-h] [--option-name OPTION_NAME_VAR] [numbers [numbers ...]]
positional arguments:
numbers
optional arguments:
-h, --help show this help message and exit
--option-name OPTION_NAME_VAR