PyCharm对`__debug__`的运行与调试行为出现意外情况。

huangapple go评论46阅读模式
英文:

Unexpected PyCharm run vs debug behavior for __debug__

问题

我有以下的Python代码

```python
def main():
    if __debug__:
        print("debug mode")
    else:
        print("non debug")

if __name__ == '__main__':
    main()

无论我运行文件还是调试它,它总是打印出"debug mode"。这不是我预期的结果。我的调试代码块计算成本很高,所以我希望只在PyCharm的调试模式下运行它(而不是在生产环境中运行)。


<details>
<summary>英文:</summary>

I have the following python code: 

```python
def main():
    if __debug__:
        print(&quot;debug mode&quot;)
    else:
        print(&quot;non debug&quot;)


if __name__ == &#39;__main__&#39;:
    main()

No matter whether I run the file or debug it, it always prints "debug mode". this is not what I would have expected. My debug block is computationally costly, so I Would prefer to only run it on my development machine if I am in debug mode in pycharm (and never in prod).

答案1

得分: 1

我的调试块在计算上成本很高,所以我希望只在我在PyCharm中处于调试模式时在开发机器上运行它(而且绝不在生产环境中运行)。

这正是为什么Python中存在优化标志的原因。

使用优化标志

因为当您不使用优化标志时,__debug__ 为真。

将这添加到运行配置的 "解释器选项" 中:-O

您可以在Python CLI中使用相同的行为:

$ python file.py
调试模式
$ python -O file.py
非调试

有关 -O 标志的更多详细信息:运行Python时 "-O" 标志的用途是什么?

英文:

> My debug block is computationally costly, so I Would prefer to only run it on my development machine if I am in debug mode in pycharm (and never in prod).

This is exactly why the optimization flag exist in Python.

Use optimization flag

Because __debug__ is true when you don't use the optimization flag.

Add this to the run configuration "Interpreter options": -O

You can get the same behavior with python in CLI:

$ python file.py
debug mode
$ python -O file.py
Non debug

More details on -O flag: What is the use of the "-O" flag for running Python?

huangapple
  • 本文由 发表于 2023年2月8日 18:31:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定