0

Python version: 3.8.5

File structure

MainDir
   |
   | Utils --|
   |         | module1.py
   |         | module2.py
   |
   | Tests --|
             | test.py

module1.py imports module2.py test.py imports module1.py

When I run python Tests/test.py I get the following error:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    import Utils.module1
  File "<abspath>/MainDir/Utils/module1.py", line 16, in <module>
    import module2
ModuleNotFoundError: No module named 'module2'

I've tried the following:

1.) Python - Module Not Found

2.)

$export PYTHONPATH="$PWD"

3.) I've tried putting the test.py file at the same level as the Utils directory.

4.)

import sys
sys.path.append("../MainDir")

And several variations thereof.

They all failed.

The only thing that worked was just putting test.py in the Utils directory and running it from there. But I know there has to be a way to get it to work when it's in its own directory.

What am I missing?

UPDATE

The selected answer worked when trying to run test.py, but it broke when trying to run module1.py.

After some more research, running it with the -m flag and package syntax worked; in my case:

python -m Utils.module1

Hope this helps anyone else who runs into this problem.

2
  • you need to add a __init__.py file to the Utils directory so that python recognizes it as a package... check the doc here Commented Aug 10, 2021 at 13:48
  • @raphael Should have mentioned that I already tried that. Didn't work; had the exact same error. Commented Aug 10, 2021 at 13:59

2 Answers 2

1

You may want to use relative imports.

So perhaps something like :

# in module1.py

import .module2

Relative imports mean that you are not trying to import from the __main__ file but from the current file (in your case module1.py).

Edit : Just realised I am stupid. This works for modules, not individual files. Please try again with from . import module2

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

2 Comments

Just tried it, but it gave me an invalid syntax error pointing right at the dot preceding module2...
The edited answer worked beautifully. Thanks!
0

if you structure your project like here you can use this. Also it is recommended to use relative import inside your packages

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

2 Comments

What's the difference between sys.path.insert() and sys.path.append()?
@Chaos_Is_Harmony, the difference is that the new path is added at the beginning of the list, shifting everything else to the right. It affects the order things are looked into (first or last ?). If you don't care about that, then insert(0, ...) might be slightly longer (O(N) instead of O(1) for append).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.