PyCharm Python script run error "ImportError: attempted relative import with no known parent package"

When trying to run a Python script in PyCharm via a run configuration, you might hit an error like this:

Traceback (most recent call last):
  File ".../__main__.py", line 3, in <module>
    from ...
ImportError: attempted relative import with no known parent package

Process finished with exit code 1

You might be able to resolve this by setting up the PyCharm run configuration as a “Module name” rather than a “Script path”.

Go to the run configuration drop down menu and click “Edit Configurations…”

At the top left of the “Configuration” tab there’s a label that says “Script path” with a drop-down arrow next to it. Click on that and select “Module name”.

Enter the Python module name that you would use to run this on the command line with python -m.

With a bit of luck this will let you run the module in PyCharm with the benefit of the various IDE tools such as the Python debugger.


Tech mentioned