вы должны использовать модуль argparse
Python для анализа параметров CLI. Я написал для вас пример.
Официальная документация argparse
: https://docs.python.org/3/library/argparse.html
Код:
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument(
"-f",
dest="first_string",
help="Your first string parameter",
required=True,
)
parser.add_argument(
"-t",
dest="second_string",
help="Your second string parameter",
required=True,
)
parser.add_argument(
"-i",
dest="third_string",
help="Your third string parameter",
required=True,
)
input_parameters, unknown_input_parameters = parser.parse_known_args()
# Set CLI argument variables.
first_arg = input_parameters.first_string
second_arg = input_parameters.second_string
third_arg = input_parameters.third_string
print("-f: {}\n"
"-t: {}\n"
"-i: {}".format(first_arg, second_arg, third_arg))
Некоторый вывод:
>>> python3 test.py -f "string1" -t "string2" -i "string 3 some directory path"
-f: string1
-t: string2
-i: string 3 some directory path
>>> python3 test.py -t "string1" -f "string2" -i "string 3 some directory path"
-f: string2
-t: string1
-i: string 3 some directory path
>>> python3 test.py -t "string1" -f "string2" -i "string 3 some directory path" -x "Unused"
-f: string2
-t: string1
-i: string 3 some directory path
>>> python3 test.py -t "string1" -i "string 3 some directory path"
usage: test.py [-h] -f FIRST_STRING -t SECOND_STRING -i THIRD_STRING
test.py: error: the following arguments are required: -f
>>> python3 test.py -h
usage: test.py [-h] -f FIRST_STRING -t SECOND_STRING -i THIRD_STRING
optional arguments:
-h, --help show this help message and exit
-f FIRST_STRING Your first string parameter
-t SECOND_STRING Your second string parameter
-i THIRD_STRING Your third string parameter