0

I have the following python package structure

configuration /
          __init__.py
          scripts  /
               __init__.py
               packageA     /
                     __init__.py
                     my_file_1.py
               packageB    /
                     __init__.py
                     my_file_2.py

In the file my_file_1.py, I have an import statement which imports a class from my_file_2.

The import statement looks like:

from configuration.scripts.packageB.my_file_2 import myClassA

Now when I run my program (my_file_1.py) I always get this error that

ImportError: No module named configuration.scripts.packageB.my_file_2

To run the program. I am running the following command:

python my_file_1.py 

I can't figure out what I am doing wrong since I have init.py files in my package structure as well. I tried using sys.path.append, but that messes up things when I write python unit tests. Can somebody help me figure what's going wrong?

chrisrhyno2003
  • 3,906
  • 8
  • 53
  • 102
  • How are you running your program? What command are you using, and from what working directory? – jwodder Jun 21 '18 at 20:42
  • are you using python2.7 or you are using python 3? – girish946 Jun 21 '18 at 20:42
  • You might have to add the path to your project directory to the PYTHONPATH environment variable. – mxdg Jun 21 '18 at 20:45
  • I'm using python 2.7 – chrisrhyno2003 Jun 21 '18 at 20:48
  • could you please fix mistypes in the snippets, like packageB vs pacakgeB. Or maybe you have similar errors in your project? – NobbyNobbs Jun 21 '18 at 20:52
  • Possible duplicate of [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – MoxieBall Jun 21 '18 at 20:57
  • @NobbyNobbs: Fixed the typos as well and still I face the same problem – chrisrhyno2003 Jun 21 '18 at 21:33
  • @MoxieBall: I looked at that post as well. As I mentioned appending the path to the system path using sys.path works, but my unit tests are unable to resolve the path when they run – chrisrhyno2003 Jun 21 '18 at 21:40
  • Ah, it sounds to me like this is a problem with unit tests! You might want to rewrite your question so that you explain how you're doing the testing as the generic import problem is most definitely a PYTHONPATH issue as you have yourself explained. – Noah Jun 21 '18 at 22:44
  • @Noah: I don't think so. Like, I'm kind of missing a point as to whether manually adding the current working directory to the path is absolutely required. I was under the assumption that init.py basically helps you discover modules within packages. But maybe not in this? – chrisrhyno2003 Jun 22 '18 at 19:26

0 Answers0