如果我在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()我看到__debug__变量被设置为0,因为没有到达‘`print("hello")调用。但是,如果我在python文件中写入相同的行并按照通常的方式运行它,如下所示
$ cat debugprint.py
if __debug__:print("hello")
$ python3 debugprint.py -O
hello然后我们看到文本"hello",这意味着__debug__仍然是真的。你知道怎么解决这个问题吗?
发布于 2020-02-22 11:43:44
您需要将-O传递给Python,而不是传递给脚本。为此,您可以将开关放在命令行的脚本文件前面:
python3 -O debugprint.py
# ^^ ^^ ^^ any script command-line args go here.
# | \ scriptname
# arguments to Python itself脚本名称后面的任何命令行参数都将传递给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或者,也可以将PYTHONOPTIMIZE environment variable设置为非空值:
$ export PYTHONOPTIMIZE=1
python3 /tmp/test.py # no command-line switches
[]
Falsehttps://stackoverflow.com/questions/60351790
复制相似问题