Importing a package from a subdirectory or relative path

Here's my directory setup:

mydir
β”œβ”€β”€ script1.py
└── shared
    β”œβ”€β”€ otherstuff
    β”œβ”€β”€ script2.py
    └── pkg
        β”œβ”€β”€ box.py
        └── __init__.py

      

script2.py

begin with

import pkg 

      

and it works great. When I include the same line in script1.py

I get:

Traceback (most recent call last):
  File "script1.py", line 1, in <module>
    import pkg

      

Is there a good way to get a syntax that's easy to work with script1.py

? I've been reading about PYTHONPATH

and sys.path

for the last hour, but I'm trying to make some basic functionality available to my repo and I can't believe it will require a change PYTHONPATH

every time I want to run the script.

What am I missing here? What's the best way to get pkg

in script1.py

?

+3


source to share


3 answers


You need to do:

from shared import pkg

      



Also, your directory shared

must have a file__init__.py

0


source


I've tested in python 3.x, you can do either -

import shared.pkg

      



or

from shared import pkg

      

0


source


If you don't want to create a file __init__.py

in shared

and using import shared.pkg

, you can work around this by doing the following:

import sys
sys.path.insert(0, 'shared')

import pkg

      

0


source







All Articles