简体   繁体   中英

argparse - how to pass argument from args into function?

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)

How could I pass arguments from CLI to my function arg? When someone use command:

python argp.py --most_common_cities 5

It should return 5 most common cities.

Remove nargs=1 , then args.most_common_cities will be the actual value passed in.

nargs=1 wraps it in a list.

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'>

I started your script with following command:

python3 test.py --most_common_cities 5

You can access the arguments with:

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']


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM