Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import python module NOT on path

I have a module foo, containing util.py and bar.py.

I want to import it in IDLE or python session. How do I go about this?

I could find no documentation on how to import modules not in the current directory or the default python PATH. After trying import "<full path>/foo/util.py", and from "<full path>" import util

The closest I could get was

import imp
imp.load_source('foo.util','C:/.../dir/dir2/foo')

Which gave me Permission denied on windows 7.

like image 901
Vort3x Avatar asked Apr 15 '12 11:04

Vort3x


People also ask

Why can't Python find my module?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

How do I import a module from a specific path?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

How do I set the path for a Python module?

To make sure Python can always find the module.py , you need to: Place module.py in the folder where the program will execute. Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can place the module.py in one of the folders included in the PYTHONPATH variable.


3 Answers

One way is to simply amend your path:

import sys
sys.path.append('C:/full/path')
from foo import util,bar

Note that this requires foo to be a python package, i.e. contain a __init__.py file. If you don't want to modify sys.path, you can also modify the PYTHONPATH environment variable or install the module on your system. Beware that this means that other directories or .py files in that directory may be loaded inadvertently.

Therefore, you may want to use imp.load_source instead. It needs the filename, not a directory (to a file which the current user is allowed to read):

import imp
util = imp.load_source('util', 'C:/full/path/foo/util.py')
like image 193
phihag Avatar answered Oct 11 '22 16:10

phihag


You could customize the module search path using the PYTHONPATH environment variable, or manually modify the sys.path directory list.

See Module Search Path documentation on python.org.

like image 32
icecrime Avatar answered Oct 11 '22 16:10

icecrime


Give this a try

import sys
sys.path.append('c:/.../dir/dir2')
import foo
like image 2
Levon Avatar answered Oct 11 '22 17:10

Levon