运行 python3 使用 -O 将调试设置为 OFF
Running python3 with debug set to OFF with -O
如果我 运行 python3 -O
在 bash 上喜欢:
(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__
仍然为真。
你知道如何解决这个问题吗?
您需要将 -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
[]
False
如果我 运行 python3 -O
在 bash 上喜欢:
(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__
仍然为真。
你知道如何解决这个问题吗?
您需要将 -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
[]
False