5

I'd like to take some actions in my code, conditioned on whether the PyCharm debugger is attached and running — e.g., I've launched my code using the IDE's "Debug" command; something like

if pycharm_debugger_is_running:
    do_something()
else:
    do_another_thing()

Is there a way to do that?

orome
  • 45,163
  • 57
  • 202
  • 418

2 Answers2

12

Since Pycharm debugger has been merged with Pydev's, you may like this answer.

Edit

In order to determine whether the script was launched by Pycharm, I can think of manually adding your own environment variable in the Run/Debug Configurations

environ pycharm

And then check for it:

if 'PYCHARM' in os.environ:
    print("running in Pycharm")

Actually the most convenient way would probably be to directly edit the default run configuration to automatically integrate that flag in any new run.

default run config pycharm

Community
  • 1
  • 1
Arnaud P
  • 12,022
  • 7
  • 56
  • 67
4

While setting your own environment variable works, I wanted something that was immutable, so there was no chance I could forget to include, or have to add something to every single project configuration. I found that in the modules PyCharm loads.

import sys

we_are_in_pycharm = '_pydev_bundle.pydev_log' in sys.modules.keys()

if we_are_in_pycharm:
    print("running in Pycharm")