IDE 和命令行中的不同结果,布尔值似乎改变了值

Different result in IDE and command line, Boolean seems to change value

我有一个 Python 3 程序,其中我有一个奇怪的行为,我将其简化为下面非常基本的 MWE:

# -*- coding: utf-8 -*-
# basic_test.py
import argparse

def fun(arg1):
    print("arg1 value right before test: ", arg1)
    if arg1:
        print("inside test")

# fun(False) # comment if not in IDE mode

### comment following section if in IDE mode
if __name__ == "__main__":
    argparser = argparse.ArgumentParser()
    argparser.add_argument("-a")

    args = argparser.parse_args()

    fun(args.a)

如果我通过调用 python basic_test.py -a False 在命令行中 运行 上面的代码,我会得到以下奇怪的(在我看来)输出:

arg1 value right before test:  False
inside test

所以不知何故 arg1 在一行是 False,而在下一行是 True,因为输入了 if 部分?为什么会这样?

此外,如果我注释 'main' 部分,并取消注释 fun(False) 行,并且 运行 该代码变成 IDE (在我的例子中是 Spyder),它 运行s 如我所料,输出如下:

arg1 value right before test:  False

所以它确实没有进入 if 部分。

如果重要的话,我正在 运行宁 Python 3.7.6 Windows。

False 你从 argparse 得到的是字符串,不像你的综合检查,它是实际的布尔值。

Argparse 没有对布尔文字的隐式解析,所以除了手动解析它们之外,最好的方法是使用 action='store_false' 并将参数作为标志传递