argparse lib in Python | Writing python scripts

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
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-12-31

Licensed under

Comments