argparse-如何将参数从args传递给函数?

时间:2020-08-09 19:12:59

标签: python argparse

import argparse
from queries import most_common_cities

parser = argparse.ArgumentParser(description='A script that does operations with database data and returns values')

parser.add_argument('-c', '--most_common_cities',
                nargs=1,
                type=positive_int,
                help='Specify how many common cities.')

args = parser.parse_args()

if args.most_common_cities:
result = most_common_cities(n) # "n" should be an arg passed by user
print(result)

如何将CLI中的参数传递给函数arg? 当有人使用命令时:

python argp.py --most_common_cities 5

它应该返回5个最常见的城市。

2 个答案:

答案 0 :(得分:1)

删除nargs=1,然后将args.most_common_cities作为传入的实际值。

nargs=1将其包装在列表中。

parser.add_argument('-c', '--most_common_cities',
                type=int,
                help='Specify how many common cities.')

args = parser.parse_args(['-c', '5'])
n = args.most_common_cities
print(n)
print(type(n))
# 5
# <class 'int'>

答案 1 :(得分:-1)

我使用以下命令启动了脚本:

python3 test.py --most_common_cities 5

您可以通过以下方式访问参数:

import argparse

parser = argparse.ArgumentParser(description='A script that does operations with database data and returns values')

parser.add_argument('-c', '--most_common_cities',
                nargs=1,
                type=int,
                help='Specify how many common cities.')

args = parser.parse_args()

arguments = vars(parser.parse_args())
print(arguments) #{'most_common_cities': [5]}

#then you can access the value with:
arguments['most_common_cities']