天天看點

python增加參數,python – 根據初始參數的值為argparse添加參數

那這個呢?

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-mode', choices=['download', 'upload'], required=True)

parser.add_argument('-d', required=True)

parser.add_argument('-f')

args = parser.parse_args()

if args.mode == 'download' and not args.f:

parser.error('-f argument is required in "download" mode.')

DEMO:

$python test.py -mode=upload -d 10

$python test.py -mode=download -d 10

usage: test.py [-h] -mode {download,upload} -d D [-f F]

test.py: error: -f argument is required in "download" mode.

$python test.py -mode=download -d 10 -f 10