我如何创建自定义标签以在命令行中获取输入字符串并将它们存储在 Python 中的变量中

How do i create custom tags for taking the input string in command line and store them in a variable in Python

输入的格式为:

myprogram.py -f "string1" -t "string2" -i "string 3 some directory path"

您应该使用 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