使用argparse显示主题

时间:2018-07-25 16:50:23

标签: python python-3.x 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()

3 个答案:

答案 0 :(得分:0)

像这样python script.py marker value调用脚本时,可以通过调用value

在脚本中访问location = args.marker

答案 1 :(得分:0)

您所拥有的一切都很好;您只需要知道从何处获取参数即可。

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的返回值为每个自变量都有一个属性,其名称取自自变量的名称。

答案 2 :(得分:0)

如果您确实确定要使用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