0

I have three folders:

/main
    __init__.py
    main.py
    /p1
        __init__.py
        p1.py
    /p2
        __init__.py
        p2.py

However some parts of p1 depend on p2 and the way in which I import p2 from p1 is by using an absolute package and not a relative one:

from main.p2.p2 import p2class

The problem arises when I want to run p1 individually by typing in:

cd main\p1 
python p1.py

However, it says:

ImportError: No module named main.p2.p2

How can I run it individually?

Sources for the files are shown below:

main\p1\p1.py:

from main.p2.p2 import p2print

def p1print():
    print "p1 printing"

if __name__ == "__main__":
    p2print()
    p1print()

main\p2\p2.py:

def p2print():
    print "p2 printing"

if __name__ == "__main__":
    p2print()
1
  • 1
    If you want to run the code exactly the way you say, you can set PYTHONPATH for your environment to absolute path till main. I assume this should help. Commented Mar 4, 2015 at 11:52

2 Answers 2

1

From outside of the /main directory, run it using python -m.

➜ python -m main.p1.p1
p2 printing
p1 printing
Sign up to request clarification or add additional context in comments.

Comments

0

You will have to import from p2.p2 instead of main.p2.p2 since the base package is inside main. If you wish to do main.p2.p2, you will have to insert the path of the main folder into sys.path

1 Comment

Yes thats what im trying to avoid doing, as this approach will work in some cases but not in all. Changing the code to support one case but not the other seemed like a bad idea

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.