Home > database >  Python import modules from different directory
Python import modules from different directory

Time:03-01

I am creating a project with so many modules, each module has helpers.py file that uses some functions from that file. here is my directory structure:

│   main.py
├───modules
│   │   __init__.py
│   ├───main
│   │       main.py
│   │       __init__.py
│   │
│   ├───network
│   │   │   helpers.py
│   │   │   network.py
│   │   │   __init__.py
│   │

main.py:

from modules.main import main

if "__main__" == __name__:
    main()

modules/main/main.py:

import sys 
sys.path.insert(0, 'J:\\Scanner\\modules')

import network.network as HostDiscovery

modules/network/network.py:

from helpers import ips
...

Whenever I try to run main.py in the root directory, I get the error:

from helpers import ips
ModuleNotFoundError: No module named 'helpers'

Each module works fine when I try running it alone, but when I run from main.py it fails with the error that it cant find helpers module. How can I achieve this without having to change the directory structure.

CodePudding user response:

I can think of two ways to solve.

  1. add source root to sys.path to top of every main file

Whenever you want to import something, the import path should start from the root. Of course some directory tranversing might be necessary because you don't want hardcode the root path, right?

This is a common practice for ISE such as pycharm, which has an option to let you add source root to path(when running from pycharm), and the option is needed for intellisense to work.

  1. try relative import

such as from .foo import bar, or from ..foo import bar. I think you need read docs yourself.

CodePudding user response:

I guess you can add to the Python path at runtime:

# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')

import file

Dunno if this helps, I'm new to Python.

  • Related