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

Question:

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 ?

Asked By: WestCoastProjects

||

Answers:

I would try running the code from the CLI to see if you get a similar error. If it works from the CLI then it maybe your console configuration. If it doesn’t work there either, then it can be one of two things:

  1. pathing issue
  2. module isn’t coded properly

If the module is correctly made, and in you current path, you should be able to just import it:

import utils

If this isn’t working then maybe you didn’t setup your module properly. For more info, see python docs on modules: https://docs.python.org/3/tutorial/modules.html

If your custom module isn’t in your current path, you may have to update the system path so that it can find your module.

import sys
sys.path.append('C:\Users\myUserName\myDir') ## Add specific directory (windows 10)
sys.path.appen('/home/myUserName/myDir') ## Add specific directory (Unix/Linux example)
sys.path.append('..') ## Add parent directory

## Now that the system path has been updated, you can load your module
import myModuleName
from myModuleName import myClassName

One last tying to try is changing into the directory where the code resides and then run the python command from there. Sometimes it is a pathing issue. If this approach works, then write a bash/sh wrapper script which changes into the directory first then runs code.

To better understand which path your python code is running from, try running the code:

import os
print('cwd: %s' % os.getcwd())

Output:

cwd: C:Usersrbalacodetest
Answered By: Randy B.

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.

Answered By: napuzba

So as napuzba stated in the accepted answer, you can add to the script.

If the location you wish to add is always relative to the venv location, which is accessible via an environment variable VIRTUAL_ENV, you can do something like adding the
following to the above accepted answer:

import os
import pathlib
sys.path.append( str(pathlib.Path(os.environ["VIRTUAL_ENV"], '..', 'imaging_lib' )))

I was in hunt for a solution, didn’t find where PyCharm provided a way to get the root project dir in a simple manner. I had found that the VIRTUAL_ENV was available, which is just under the project root directory in my case.

So simply ascending up a level provided the project root, then adding a relative directory below the project root, in this example case, the directory imaging_lib. Using pathlib provided a clean, simple way to create the path, appropriate for the os file path format.

This provided a solution for myself.

Answered By: Otto Hirr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.