Search code examples
pythonpycharmconsole

How to do a relative import when using Pycharm "Run in python console"?


I am using Pycharm and its Run in python console feature. It works well except when the source file is intended to be run as a module (-m option).

For example if a python source file includes:

from . import utils

Then when selecting a snippet - via Run in python console - that includes/requires that import we get:

importError: attempted relative import with no known parent package

Is there any way to run this code in Pycharm console ?


Solution

  • You can edit and adjust the starting script to your needs.


    Go to Settings > Build, Execution, Deployment > Console > Python Console. You should find the following starting script:

    import sys; print('Python %s on %s' % (sys.version, sys.platform))
    sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])
    

    Now, You can adjust the script to your needs so it will not raise the errors related to relative imports.