Home > Back-end >  How can I import my personnal modules in python?
How can I import my personnal modules in python?

Time:02-20

I have a problem with my python modules for a project. Here's my tree for my project :

Documents/Projects/projet/
├── code
│   ├── datas
│   │   ├── Lexique383
│   │   │   └── Lexique383.tsv
│   │   └── Lexique383.zip
│   ├── __init__.py
│   ├── __pycache__
│   │   └── __init__.cpython-38.pyc
│   ├── src
│   │   ├── Correcteur.py
│   │   ├── __init__.py
│   │   ├── PoCCode.py
│   │   └── __pycache__
│   │       ├── Correcteur.cpython-38.pyc
│   │       └── __init__.cpython-38.pyc
│   └── ui
│       ├── GUI.py
│       ├── GUI.ui
│       ├── __init__.py
│       ├── Loader.py
│       └── __pycache__
│           └── GUI.cpython-38.pyc

The dependencies are like :

  • GUI.py uses Correcteur.py
  • Loader.py uses GUI.py

I am working on 2 computers for this project, one with PyCharm and one with VSCode. The thing is I used PyCharm to run Loader.py with a configuration where it added content roots and source roots to PYTHONPATH. But when i went back to my other computer and wanted to check if everything worked fine, I had this error :

Traceback (most recent call last):
  File "Documents/Projects/projet/code/ui/Loader.py", line 4, in <module>
    import GUI
  File "Documents/Projects/projet/code/ui/GUI.py", line 13, in <module>
    from code.src import Correcteur
ModuleNotFoundError: No module named 'code.src'; 'code' is not a package

So I tried to add to my syspath "code", "src" and "ui", but I still have the error. Without a doubt I did something that didn't work with sys.path but I can't figure out what. Could you please help me on this matter?

Edit : This is how I added directories to my syspath using pathlib.
Loader.py :

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication
import sys
from pathlib import Path
sys.path.extend([
    Path(__file__).parents[1].resolve(),
    Path(__file__).parents[1].resolve() / "src"
])
print(sys.path)
import GUI

And here is how I imported Correcteur in GUI.py :

from code.src import Correcteur

CodePudding user response:

Your method of adding to sys.path should work. The main issue is that you are adding pathlib.Path objects to sys.path, which only expects strings.

If you just cast the Path object you're trying to add to a string, then a simplified version of your code should work:

In Loader.py

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication
import sys
from pathlib import Path
# Note the call to `str(...)` here
sys.path.insert(1, str(Path(__file__).parents[2].absolute()))
print(sys.path)
import GUI

Additionally, some of the errors that you are getting are because Python has a builtin module named code, which it's importing by mistake, so I would recommend changing your package to have a different name.

  • Related