为了解决@kcpr对@Honza Osobne的(当前接受的)答案的评论
不幸的是,它不起作用,然后参数将其定义为默认值。
首先可以通过将参数与 Namespace
提供default=argparse.SUPPRESS
选项对象abd(请参见@hpaulj和@Erasmus Cedernaes的答案以及此python3 doc),如果未提供参数,则将其设置为默认值。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args:
# the argument is in the namespace, it's been provided by the user
# set it to what has been provided
theinfile = args.infile
print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
# the argument isn't in the namespace
# set it to a default value
theinfile = 'your_default.txt'
print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
用法
$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt
$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt
isset()
是什么(提示:Python不是PHP)?hasattr()
也许是您的意思吗?为什么不配置argparse为选项设置默认值呢?