5

I have the following code structure running perfectly fine in my IDE(Aptana Studio):

/ProjectName/
    /lib
    /src
        /Module1
        /Module2
        /Module3
         __init__.py
         pyClass.py         ##Python Class
        /main
         main.py

main.py :

import Module3.pyClass as pc

myClass=pc.pyClass()

but when I try to run it from command line , import error !

importError: No module named Module3.pyClass

I am running from the /main directory. Is it because it doesn't know where to find Module3 to import?How should i tell where it should look for Module3 ?

Thank you.

3
  • 2
    Could you please add the following lines in your main.py before the import and give us the output : import sys, print sys.path. If you don't find /path/to/ProjectName/src/ in your Python path, you need to add it. You also need to add a init.py file in src. Commented Sep 19, 2011 at 23:05
  • Make sure that PYTHONPATH environment variable / sys.path Python variable contain /ProjectName/src/ . You might want to set PYTHIONPATH to whatever Aptana is setting it to. Commented Sep 19, 2011 at 23:07
  • Thanks but I don't know how to add it in runtime..so every user has it already setup in their machine when running my code. Commented Sep 19, 2011 at 23:33

1 Answer 1

12

The src directory isn't in the python module search path if you run it from the main directory. You'll need to either run the script from the src directory (a wrapper script, or move it) or add the src directory to sys.path. This is probably what you want. Here's how:

import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

(If you're compiling/freezing it with py2exe/py2app/cxfreeze/whatever, you'll need a slightly different solution due to the way it works.)

Sign up to request clarification or add additional context in comments.

5 Comments

I got your point but my main.py is in src/main so the above code does not add path to Modules..Would you elaborate on how to add their path when I need to distribute the code ?
@Arash Sorry, I meant dirname of dirname rather than just dirname. Fixed now.
If you can have a script in the root of src it's easier. And you can even have it just doing from main import main; main(), if you like.
Is there a difference between the code you posted earlier and the edited version?I cant see what has been edited.
@Arash There is; clicking on the "edited some time ago" link gets you a way you can see what's changed. I added another level of os.path.dirname()-calling.

Your Answer

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