argparse lib in Python | Writing python scripts

argparse (参数库)

1. sys

sys.argv[1]

2. argparse

1. Quick Start

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i','-I','--input') #输入文件
parser.add_argument('-o','-U','--output') #输入文件

##获取参数
args = parser.parse_args()
INPUT = args.input
RANGE = args.output





run as 

python3 test.py -i inputfile -o outpufile

2. Important arguments

#####
with type and default
parser.add_argument(
'--width',
dest='num_hands',
type = int,
default = 80,
help='Max number of hands to detect.')

3. Reading *.png

3.1 nargs=“+” (One/More)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i','-I','--input',nargs='+') #输入文件

args = parser.parse_args()
INPUT = args.input

print(INPUT)
$ python3.7 test.py  -i Ms*
['Msg', 'Msg2']

3.2 nargs=“?” (None/One)

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-i','-I','--input', default='a', nargs='?') #输入文件

args = parser.parse_args()
INPUT = args.input

print(INPUT)
$ python3.7 test.py
a
$ python3.7 test.py -i
None
$ python3.7 test.py -i b
b

argparse lib in Python | Writing python scripts

https://karobben.github.io/2020/01/22/Python/argparse/

Author

Karobben

Posted on

2020-01-22

Updated on

2024-01-11

Licensed under

Comments