在PyCharm中如何“部分”以调试模式运行代码

4
我想在PyCharm的调试模式下运行一些Python代码。我的代码包括一个API函数调用,但由于某种原因,在调试器模式下这个单独的函数调用需要很长时间。
我真的不关心调试那个特定的函数,让调试器跳过那个函数(只在常规模式下运行它)是可以的。然而,我希望能够在调试模式下运行我的其他代码。
在PyCharm中是否可行或者是否有任何Python解决方法?
# some code to be run in debugger mode, e.g.
func_a(obj_a) #this function modifies obj_a

# some API function call, super slow in debugger mode. can I just run this part in run mode? e.g.
obj_b = api_func(obj_a)

# rest of the code to be run in debugger mode e.g.
func_c(obj_b)

2
你不能将你想要跳过的部分注释掉吗? - Gudarzi
在调用之前设置一个断点,在调用之后设置另一个断点,然后正常执行(不要单步执行)直到下一个断点。 - Srini
@Srini 我已经尝试过使用“恢复程序”(F9)在第一个断点处运行,但它没有起作用。你所说的正常执行,是指以其他方式运行函数调用吗? - Mehdi Golari
你的问题太宽泛了,请更加具体,并补充更多细节,提供一些示例代码和 超慢的API函数调用,这样我们才能帮助你,而不是猜测。 - Azat Ibrakov
@Srini 是的,在调试器中它从来没有到达断点。在常规运行模式下,它的工作非常正常。我确认我正在使用的库在调试器模式下表现不佳。 - Mehdi Golari
显示剩余3条评论
2个回答

4

潜在地,您可以使用 sys.gettracesys.settrace 在运行您的 API 调用时移除调试器,但这并不推荐,如果您这样做,PyCharm 会向您发出警告:

PYDEV DEBUGGER WARNING:
当使用调试器时,不应使用 sys.settrace()。
这可能导致调试器停止正常工作。
如果需要,请查看:
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html
以了解如何正确恢复调试跟踪。

在您的情况下,您可以这样做:

import sys

# some code to be run in debugger mode, e.g.
func_a(obj_a) #this function modifies obj_a

# Remove the trace function (but keep a reference to it).
_trace_func = sys.gettrace()
sys.settrace(None)

# some API function call, super slow in debugger mode. can I just run this part in run mode? e.g.
obj_b = api_func(obj_a)

# Put the trace function back.
sys.settrace(_trace_func)

# rest of the code to be run in debugger mode e.g.
func_c(obj_b)

我强烈建议在调试器禁用时,尽可能保持运行的代码简短。

感谢您详细的回复,现在对我很有用。我是Python编程的新手,我知道应该有类似这样的解决方案,除非PyCharm阻止调试器的任何操作,但他们没有:) - Mehdi Golari
运行得非常好! - Mehran F Langerudi

0

你可以右键单击断点并设置条件 在此输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接