2

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?

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121
  • did you ry putting a init file in the directory where scraper.py is? – Arpit Solanki Aug 20 '17 at 15:04
  • Try to put "CustomModule.py" and "scraper.py" at the same level (in the same folder). – ziMtyth Aug 20 '17 at 15:07
  • Is this python 2 or python 3? Are any of these folders in your `sys.path`? Is `scraper.py` the `__main__` file? – Aran-Fey Aug 20 '17 at 15:08
  • 1
    @ZiMtyth all my modules will live in a different directory to the bin directory. That's not what I want. – BugHunterUK Aug 20 '17 at 15:09
  • See the bottom of this page https://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories , maybe you can find what you want – ziMtyth Aug 20 '17 at 15:12
  • may this can help https://stackoverflow.com/questions/45768862/installing-modules-in-python-3 – Kallz Aug 21 '17 at 09:42
  • Try import myproject.CusomModule. from statements work differently in python 3. Bar that. You cannot go up one level... – Jean-François Fabre Aug 21 '17 at 09:47
  • Move scraper.py up one level you will be able to use my suggestion. It proves that your directory structure is not adapted to how python works. – Jean-François Fabre Aug 21 '17 at 09:53
  • @Jean-FrançoisFabre I disagree. `scraper.py` belongs in the `bin` directory. along with other applications intended to be ran from the terminal. Python does have a solution (Yohan's comment). Python has no definitive requirements to project structure, only guidelines. If, like me, you want to do things differently ... it can handle that too. My original question was to ask if it could be done without using `sys.path.append` (which I was already using) – BugHunterUK Aug 21 '17 at 18:15
  • as you want, it's your project after all. It's just that "parent directory" cannot be a module. You could set pythonpath too. – Jean-François Fabre Aug 21 '17 at 19:50

1 Answers1

1

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
Yohan Grember
  • 587
  • 5
  • 13