使用 argparse 显示主题
Display a subject using argparse
我的目标是使用 argparse(CLI) 向用户提出问题,然后以类似于以下的方式将输入存储为字符串:
marker = input("Name of marker: ")
Location = input("Name of location: ")
我不知道该怎么做,但这是我目前拥有的:
parser = argparse.ArgumentParser(description = 'Collect Information')
parser.add_argument('marker', help = 'Name of marker')
parser.add_argument('location', help = 'Name of location')
args = parser.parse_args()
像这样调用脚本时 python script.py marker value
您可以通过调用 location = args.marker
在脚本中访问 value
你拥有的一切都很好;你只需要知道去哪里寻找参数。
parser = argparse.ArgumentParser(description='Collect Information')
parser.add_argument('marker', help='Name of marker')
parser.add_argument('location', help='Name of location')
args = parser.parse_args()
print("Your marker is {}".format(args.marker))
print("Its location is {}".format(args.location))
通常,parse_args
的 return 值对每个参数都有一个属性,其名称取自参数的名称。
如果您真的确定要使用 argparse
来做这类事情,那么您已经掌握了其中的大部分内容:
import argparse
parser = argparse.ArgumentParser(description = 'Collect Information')
parser.add_argument('-m', '--marker', dest='marker', type=str, help = 'Name of marker', required=True) # The required argument is optional here and defaults to False
parser.add_argument('-l', '--location', dest='location', type=str, help = 'Name of location', required=True)
args = parser.parse_args()
marker = args.marker
location = args.location
但是,请注意 help
消息只会在用户键入以下命令时显示:python name_of_your_script.py --help
.
我的目标是使用 argparse(CLI) 向用户提出问题,然后以类似于以下的方式将输入存储为字符串:
marker = input("Name of marker: ")
Location = input("Name of location: ")
我不知道该怎么做,但这是我目前拥有的:
parser = argparse.ArgumentParser(description = 'Collect Information')
parser.add_argument('marker', help = 'Name of marker')
parser.add_argument('location', help = 'Name of location')
args = parser.parse_args()
像这样调用脚本时 python script.py marker value
您可以通过调用 location = args.marker
value
你拥有的一切都很好;你只需要知道去哪里寻找参数。
parser = argparse.ArgumentParser(description='Collect Information')
parser.add_argument('marker', help='Name of marker')
parser.add_argument('location', help='Name of location')
args = parser.parse_args()
print("Your marker is {}".format(args.marker))
print("Its location is {}".format(args.location))
通常,parse_args
的 return 值对每个参数都有一个属性,其名称取自参数的名称。
如果您真的确定要使用 argparse
来做这类事情,那么您已经掌握了其中的大部分内容:
import argparse
parser = argparse.ArgumentParser(description = 'Collect Information')
parser.add_argument('-m', '--marker', dest='marker', type=str, help = 'Name of marker', required=True) # The required argument is optional here and defaults to False
parser.add_argument('-l', '--location', dest='location', type=str, help = 'Name of location', required=True)
args = parser.parse_args()
marker = args.marker
location = args.location
但是,请注意 help
消息只会在用户键入以下命令时显示:python name_of_your_script.py --help
.