0

I'm using: Python 2.7 and a virtual environment that I created using python -m virtualenv venv

I will not accept manipulating the python path as an answer

So I've been trying up and down to create a python file in my project directory that I can import but no matter what I do I keep getting the same ImportError saying there is no module with that name. Here is my file structure:

programs
|__ project
    |__ __init__.py
    |__ utility.py
    |__ dirA
    |   |__ __init__.py
    |   |__ subdirA
    |       |__ venv
    |       |__ __init__.py
    |       |__ mainA.py
    |__ dirB
        |__ __init__.py
        |__ subdirB
            |__ venv
            |__ __init__.py
            |__ mainB.py

Inside mainA.py these are the imports that I have tried:

from project.utility import some_function
from project.utility import *
from project import utility
import project.utility

But no matter what I do when I try to run my program using python mainA.py I repeatedly get and ImportError saying that no module named project.utility. The ultimate goal is to be able to use utility.py functions within any sub-directories of project.

I've tried even doing simple examples with smaller directory structures but I cannot get it to import other files.

Chiken
  • 23
  • 6
  • 2
    In order for the Python to import your `project` package, its containing directory (`programs`) needs to be on the Python path. How is `programs` being added to the Python path? Ordinarily, you'd need to either install your project as distribution package or rely on having your CWD be `programs` for this to be the case. – Brian61354270 Feb 06 '23 at 19:19
  • 1
    Running `python mainA.py` would never work, since that treats `mainA.py` as being a top-level script that isn't part of a package. You'd need to use `python -m project.dirA.subdirA.mainA` – Brian61354270 Feb 06 '23 at 19:22
  • Also, as I'm sure you already know, [all support for Python 2.x was dropped in January 2020](https://www.python.org/doc/sunset-python-2/). Any outstanding bugs and security issues are going to remain indefinitely. You should strongly consider upgrading to an active version of Python as soon as possible. – Brian61354270 Feb 06 '23 at 19:26
  • @Brian Regarding upgrading Python, Unfortunately I don't have control over that at but it's something that will be coming soon. – Chiken Feb 06 '23 at 19:50
  • @Brian There is a lot to unpack here but all really good info. Ultimately I think that link about Relative imports does solve the question, and understanding what's happening when I run `mainA.py` as a top-level script. I will need to sit with this info and read through it to fully unpack it, but thank you for the references. – Chiken Feb 06 '23 at 19:52
  • @Brian I have not added programs to the Python path, I will read up on it but I saw a lot of people talking about sys.path and how manipulating the python path was not the correct answer. – Chiken Feb 06 '23 at 19:53

0 Answers0