1

I have a project arranged like so:

Project
└── test
    ├── main.py
    │  
    └── x.py
    │  
    └── y.py

I try to run the tests by executing python -m test.main.py from the project directory, but I get an error that says ModuleNotFoundError: No module named x.

main.py contains:

from x import c, k
import y

Why do I get this error, and how can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
DonBebo97
  • 11
  • 3
  • Are x and y the actual names or standin names? make sure the names of the files don't collide with any other packages installed or in the standlib. – saquintes Jan 13 '23 at 10:14
  • Welcome to Stack Overflow. Use *relative import*, as explained in the linked duplicates. In short, `from .x import c, k`, and `from . import y`. Since you are running the code from a parent of the `test` folder, it will all be seen as in an appropriate package, allowing these to work. The error occurs because `from x import c, k` and `import y` ask for *absolute* imports, which will check a list of specific places for the modules - and your `test` folder isn't on that list. – Karl Knechtel Jan 13 '23 at 10:32
  • 1
    As an aside, the command `python -m test.main.py` is definitely a typo. When using the `-m` flag, specify a **qualified module name, not** a source file name (i.e., do not include `.py` at the end - this command would mean to look in a sub-package folder named `main`, for a file called `py.py` representing the `py` module). For the folder structure that you show, you should instead run `python -m test.main`. – Karl Knechtel Jan 13 '23 at 10:37

0 Answers0