我想给我的Python3代码提供可选参数。我正在使用argparse
def main():
parser = argparse.ArgumentParser(description="Solution")
parser.add_argument("size", help="sector size")
parser.add_argument("name", help="Disk name", required = False)
args = parser.parse_args()
sec_size = args.size
if not args.name :
print('Will carry only few sets of operations')
else :
name = args.name
出现错误
Traceback (most recent call last):
File "pythoncode.py", line 189, in <module>
main()
File "pythoncode.py", line 145, in main
parser.add_argument("name", help="Disk name", required = False)
File "/usr/lib64/python3.7/argparse.py", line 1335, in add_argument
kwargs = self._get_positional_kwargs(*args, **kwargs)
File "/usr/lib64/python3.7/argparse.py", line 1447, in _get_positional_kwargs
raise TypeError(msg)
TypeError: 'required' is an invalid argument for positionals
有人可以在这里指出我做错了什么吗? 谢谢。
答案 0 :(得分:1)
Required = false只能用于可选的argemnt。对于可选参数,应使用-
parser.add_argument("--name", help="Disk name", required = False)
当没有--
时,python会将其视为位置参数。因此所需的功能性论点对位置论证无效。