sazr
sazr

Reputation: 25928

Import Python file from within executing script

I am attempting to import a python file(called test.py that resides in the parent directory) from within the currently executing python file(I'll call it a.py). All my directories involved have a file in it called init.py(with 2 underscores each side of init)

My Problem: When I attempt to import the desired file I get the following error

Attempted relative import in non-package

My code inside a.py:

try:
    from .linkIO can_follow # error occurs here
except Exception,e:
     print e
print success

Note: I know that if I were to create a file called b.py and import a.py(which in itself imports the desired python file) it all works, so whats going wrong?

For eg:

b.py:

import a
print "success 2"

Upvotes: 2

Views: 533

Answers (1)

Don Question
Don Question

Reputation: 11614

As stated in PEP 328 all import must be absolute to prevent modules masking each other. Absolute means the module/package must be in the module-path sys.path. Relative imports (thats the dot for) are only allowed intra-packages wise, meaning if modules from the same package want to import each other.

So this leave you with following possibilities:

  1. You make a package (which you seem to have made already) and add the package-path to sys. path

  2. you just adjust sys.path for each module

  3. you put all your custom modules into the same directory as the start-script/main-application

for 1. and 2. you may add a package/module to sys.path like this:

import sys
from os.path import dirname, join
sys.path.append(dirname(__file__))  #package-root-directory 

or

module_dir = 'mymodules'
sys.path.append(join(dirname(__file__), module_dir)) # in the main-file

BTW:

from .linkIO can_follow

can't work! The import statement is missing!

As a reminder: if using relative imports you MUST use the from-version: from .relmodule import xyz. An import .XYZ without the from isn't allowed!

Upvotes: 3

Related Questions