0

Recently started a new Python project.

I am resolving a import module error where I am trying to import modules from the same directory.

I was following the solutions here but my situation is slightly different and as a result my script cannot run.

My project directory is as follows:

dir-parent
    ->dir-child-1
    ->dir-child-2
    ->dir-child-3
    ->__init__.py (to let python now that I can import modules from here)
    ->module1
    ->module2
    ->module3
    ->module4
    ->main.py

In my main.py script I am importing these module in the same directory as follows:

from dir-parent.module1 import class1

When I run the script using this method it throws a import error saying that there is no module named dir-parent.module1 (which is wrong because it exists).

I then change the import statement to:

from module1 import class1

and this seemed to resolve the error, however, the code I am working on has been in use for over 2.5 years and it has always imported modules via this method, plus in the code it refers to the dir-parent directory.

I was just wondering if there is something I am missing or need to do to resolve this without changing these import statements and legacy code?

EDIT: I am using PyCharm and am running off PyCharm

Community
  • 1
  • 1
SeekingAlpha
  • 7,489
  • 12
  • 35
  • 44
  • 1
    Is the directory containing `dir-parent` on the Python module search path? – BrenBarn Jan 29 '14 at 21:52
  • You are probably executing main.py from within `dir-parent`. Try changing to one directory upwards and running `python -m dir_parent.main`. You can find more info in this excellent blog post: http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/ – Brave Sir Robin Jan 29 '14 at 21:54

2 Answers2

1

If you want to keep the code unchanged, I think you will have to add dir-parent to PYTHONPATH. For exemple, add the following on top of your main.py :

import os, sys

parent_dir = os.path.abspath(os.path.dirname(__file__)) # get parent_dir path
sys.path.append(parent_dir)
Agate
  • 3,152
  • 1
  • 19
  • 30
  • Like so? parent_dir = os.path.abspath(os.path.dirname(C:\dev\hpact\src)) complains that it is not valid syntax... I am using a windows machine – SeekingAlpha Jan 29 '14 at 22:12
  • No, you can simply copy and paste : `__file__` is a variable referring to the current script. – Agate Jan 29 '14 at 22:14
  • 'parent_dir = os.path.abspath(os.path.dirname(__file__))' sys.path.append("C:\dev\hpact\src\hpact") still complains of the same issue – SeekingAlpha Jan 29 '14 at 22:34
0

Python's import and pathing are a pain. This is what I do for modules that have a main. I don't know if pythonic at all.

# Add the parent directory to the path
CURRENTDIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if CURRENTDIR not in sys.path:
    sys.path.append(CURRENTDIR)
justengel
  • 6,132
  • 4
  • 26
  • 42