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

2
  • 1
    Is the directory containing dir-parent on the Python module search path? Commented Jan 29, 2014 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: blog.habnab.it/blog/2013/07/21/python-packages-and-you Commented Jan 29, 2014 at 21:54

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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
No, you can simply copy and paste : __file__ is a variable referring to the current script.
'parent_dir = os.path.abspath(os.path.dirname(file))' sys.path.append("C:\dev\hpact\src\hpact") still complains of the same issue
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.