这通常是因为之前在代码中定义了一个 store_true 参数,但没有给它任何默认值。在某些情况下,可以通过将参数定义更改为 store_false 来解决该问题。例如:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_false', help='turn off debug mode')
args = parser.parse_args()
if args.debug:
print('Debug mode is on')
else:
print('Debug mode is off')
在这个示例中,如果使用 "--debug" 参数,则 debug 模式将关闭。如果不使用参数,则默认情况下 debug 模式将打开。
如果您确实需要使用 store_true 参数并且希望设置默认值,则可以通过将默认值更改为 False 来解决问题,如下所示:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true', default=False, help='turn on debug mode')
args = parser.parse_args()
if args.debug:
print('Debug mode is on')
else:
print('Debug mode is off')
在这个示例中,如果使用 "--debug" 参数,则 debug 模式将打开。如果不使用参数,则默认情况下 debug 模式将关闭,并且不会引发 argparse 需要参数的错误。