使用 -O 将调试设置为 OFF 运行 python3

kg_*_*g__ 2 python debugging command-line-arguments python-3.x

如果我在 bash 上运行python3 -O

(base) [xyx@xyz python_utils]$ python3 -O                                                                                                                Python 3.6.4 (default, Mar 28 2018, 11:00:11) [GCC 6.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> if __debug__:print("hello")
...
>>> exit()
Run Code Online (Sandbox Code Playgroud)

我看到__debug__变量设置为0,因为未到达 `print("hello") 调用。但是如果我在 python 文件中编写上面相同的行并以通常的方式运行它,例如

(base) [xyx@xyz python_utils]$ python3 -O                                                                                                                Python 3.6.4 (default, Mar 28 2018, 11:00:11) [GCC 6.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> if __debug__:print("hello")
...
>>> exit()
Run Code Online (Sandbox Code Playgroud)

然后我们看到文本"hello",这意味着__debug__仍然是正确的。你知道如何解决这个问题吗?

Mar*_*ers 5

您需要传递-O给 Python,而不是您的脚本。您可以通过在命令行上将开关放在脚本文件之前来执行此操作:

python3 -O debugprint.py
#       ^^    ^^          ^^ any script command-line args go here.
#        |      \ scriptname
# arguments to Python itself
Run Code Online (Sandbox Code Playgroud)

脚本名称后面的任何命令行参数都会传递给列表中的脚本sys.argv

$ cat debugargs.py
import sys
print(sys.argv[1:])
print(__debug__)
$ python3 debugargs.py -O
['-O']
True
python3 -O /tmp/test.py -O
['-O']
False
Run Code Online (Sandbox Code Playgroud)

或者,您也可以将PYTHONOPTIMIZE环境变量设置为非空值:

$ export PYTHONOPTIMIZE=1
python3 /tmp/test.py  # no command-line switches
[]
False
Run Code Online (Sandbox Code Playgroud)