1

I am working on a project structured in the following way:

repo-name/
   .venv
   src/
      __init__.py
      module1.py
      module2.py
   scratches/
      script1.py
   poetry.lock
   pyproject.toml

In script1.py I would like to use the classes defined in module1.py and module2.py, thus the file looks like:

#repo-name/scratches/script1.py

import src.module1 as m1

I am using Pycharm as IDE and I have marked src as source directory. If I run script1.py in Pycharm I do not get any error. However if I navigate into repo-name/scratches/ and run poetry shell and then run python script1.py I get the following error:

ModuleNotFoundError: No module named 'src'
   

The absolute import cannot start from repo-name due to "-" in the name of the repository.

Is there any solution to run the script without changing the structure of the repository?

1
  • Did you solve your problem? Commented Dec 27, 2020 at 12:11

1 Answer 1

1

Solution

You can do something like this:

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.dirname(__file__))

Put this code at the top of your script, before the other imports.

Explanation

with sys.path.append() you can add any folder/directory to the sys.path list. When you import stuff the interpreters looks for modules and packages in this list. So you can add your own src path to it and make the import work.

Moreover I used some os tools like os.path.dirname or os.path.join in combination with the __file__ variable to automatically add the ./../ directory (where src is) and the ./ directory (where the script is).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.