英文:
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("debug mode")
else:
print("non debug")
if __name__ == '__main__':
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?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论