BugHunterUK
BugHunterUK

Reputation: 8948

Importing a custom module from a different directory within the same project

I'm trying to import a custom module but for some reason I can't get it to work and I'm getting an ImportError.

My directory structure is like so:

MyProject
  - MyProject
    - bin
      scraper.py
    - myproject
      __init__.py
      CustomModule.py
  - web
    index.html
  - venv

I'm attempting to import CustomModule.py from scraper.py. Ideally without having to set any environment variables, or using sys.path.

This is what I've tried:

import CustomModule
from myproject import CustomModule
from ..myproject import CustomModule

Is this possible?

Upvotes: 2

Views: 73

Answers (1)

Yohan Grember
Yohan Grember

Reputation: 607

Taking Jean-François Fabre's comment into account, if no solution without sys.path is provided, consider using:

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__),'..','myproject'))
import CustomModule

Upvotes: 1

Related Questions