How to launch PyCharm's debugger with breakpoint()

Viewed 535

I understand that I can set which debugger is launched by setting sys.breakpointhook(), but what do I set it to in order to launch PyCharm's IDE?

To clarify, I want PyCharm's debugger to launch when it encounters the breakpoint() builtin, especially if I'm running the program from PyCharm.

If you're wondering "why ever do this when you could just run from the debugger?" I'm trying to debug some code that responds differently when started with the debugger.

2 Answers

PyCharm uses the pydevd debugger https://pypi.org/project/pydevd-pycharm/. So assuming you want to debug a Python application started outside of PyCharm, you have two options:

The second option is probably closer to what you have in mind, i.e. instead of setting the debugger using sys.breakpointhook, you install the debugger using pydevd_pycharm.settrace(...) which then connects to PyCharm (where you can set the breakpoints in the source files).

Installing the custom breakpointhook by pointing sys.breakpointhook to the pydevd breakpointhook (i.e. pointing to the "Pycharm Debugger") will be done by pydevd (https://github.com/fabioz/PyDev.Debugger/blob/37d804c7ac968694ce29c93392e3bed6fda641f0/pydevd.py#L95, line 117 to be precise).

Ueli's answer got me 99% of the way there. Here's the summary.

If you want the PyCharm debugger to start, all you need to do is import it. There are a couple ways:

You can use the pydevd-pycharm.egg from the PyCharm installation (<PyCharm directory>/debug-egg/pydevd-pycharm.egg) or install the pydevd-pycharm package using pip.

If you're running things locally, the simplest would just be to add

sys.path.append("<PyCharm directory>/debug-egg/pydevd-pycharm.egg")
import pydevd_pycharm

somewhere in the program you are debugging.

If you're Trying to debug on a remote machine, you will need to install pydevd-pycharm:

pip install pydevd-pycharm~=<version of PyCharm on the local machine>

before adding

import pydevd_pycharm

Somewhere in the program.

The instructions for how to import pydevd_pycharm is coppied from step 4 of https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html#remote-debug-config (as linked in Ueli's answer).

Related