简体   繁体   中英

Intellij/Pycharm can't debug Python modules

I use PyCharm / IntelliJ community editions from a wile to write and debug Python scripts, but now I'm trying to debug a Python module , and PyCharm does a wrong command line instruction parsing, causing an execution error, or maybe I'm making a bad configuration.

This is my run/debug configuration:

IntelliJ运行/调试Python模块配置

And this is executed when I run the module (no problems here):

/usr/bin/python3.4 -m histraw

But when I debug, this is the output in the IntelliJ console:

/usr/bin/python3.4 -m /opt/apps/pycharm/helpers/pydev/pydevd.py --multiproc --client 127.0.0.1 --port 57851 --file histraw
/usr/bin/python3.4: Error while finding spec for '/opt/apps/pycharm/helpers/pydev/pydevd.py' (<class 'ImportError'>: No module named '/opt/apps/pycharm/helpers/pydev/pydevd')

Process finished with exit code 1

As you can see, the parameters are wrong parsed, and after -m option a IntelliJ debug script is passed before the module name.

I also tried just put -m histraw in the Script field, but doesn't work, that field is only to put Python script paths, not modules.

Any ideas?

There is another way to make it work.You can write a python script to run your module.Then just configure PyCharm to run this script .

import sys
import os
import runpy
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
runpy.run_module('<your module name>', run_name="__main__",alter_sys=True)

Then the debugger works.

I found it easiest to create a bootstrap file (debuglaunch.py) with the following contents.

from {package} import {file with __main__}

if __name__ == '__main__':
    {file with __main__}.main()

For example, to launch locustio in the pycharm debugger, I created debuglaunch.py like this:

from locust import main

if __name__ == '__main__':
    main.main()

And configured pycharm as follows.

pycharm_debug_config

NOTE: I found I was not able to break into the debugger unless I added a breakpoint on main.main() . That may be specific to locustio, however.

In PyCharm 2019.1 (professional), I'm able to select run as module option under configurations, as below

在此输入图像描述

The problem is already fixed since PyCharm 4.5.2. See corresponding issue in PyCharm tracker: https://youtrack.jetbrains.com/issue/PY-15230

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM