0

I am trying to test Python modules. Currently, the file structure is like the following displayed:

project
├── __init__.py
├── __pycache__
│   └── __init__.cpython-37.pyc
├── p.py
├── package1
│   ├── __init__.py
│   ├── __pycache__
│   ├── module1.py
│   └── module2.py
└── package2
    ├── __init__.py
    ├── __pycache__
    └── module3.py

In the module3.py, I would like to import the functions defined in module2.py. I believe I just need to use from package1.module2 import function_name. However, that doesn't work and the error is ModuleNotFoundError: No module named 'package1'.

BTW, I am using Python3.6 for the testing.

Tim
  • 1
  • First of all, dynamically add `project` path to PYTHON PACKAGE/MODULE SEARCH PATH then try. Check https://stackoverflow.com/questions/8663076/python-best-way-to-add-to-sys-path-relative-to-the-current-running-script . – hygull Jun 30 '20 at 04:35
  • Does this answer your question? [How to fix 'no module named "app\_one"](https://stackoverflow.com/questions/62497278/how-to-fix-no-module-named-app-one) – Roshin Raphel Jun 30 '20 at 07:36
  • Thanks! Is there any solution where I don't have to bother **sys**? – Tim Jul 02 '20 at 03:36

1 Answers1

0

You need to add the directory path to your sys.path or PYTHONPATH, the following code would work. In your module3.py, add this:

import os, sys
ab_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../package1'))
sys.path.append(ab_path)

Then you can do from module2 import function_name after it.

Jeffrey
  • 184
  • 1
  • 1
  • 9
  • Thanks! That's basically my current solution. But what if I don't want to bother **sys** library? I think there are such ways provided in the [official website](https://docs.python.org/3/tutorial/modules.html#tut-packages). The problem is that it doesn't work for me even though I have the same file structure. – Tim Jul 02 '20 at 03:35