Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python imports: importing a module without .py extension?

Tags:

python

debian

In a Python system for which I develop, we usually have this module structure.

mymodule/
mymodule/mymodule/feature.py
mymodule/test/feature.py

This allows our little testing framework to easily import test/feature.py and run unit tests. However, we now have the need for some shell scripts (which are written in Python):

mymodule/
mymodule/scripts/yetanotherfeature.py
mymodule/test/yetanotherfeature.py

yetanotherfeature.py is installed by the module Debian package into /usr/bin. But we obviously don't want the .py extension there. So, in order for the test framework to still be able to import the module I have to do this symbolic link thingie:

mymodule/
mymodule/scripts/yetanotherfeature
mymodule/scripts/yetanotherfeature.py @ -> mymodule/scripts/yetanotherfeature
mymodule/test/yetanotherfeature.py

Is it possible to import a module by filename in Python, or can you think of a more elegant solution for this?

like image 603
pojo Avatar asked Dec 18 '22 07:12

pojo


1 Answers

The imp module is used for this:

daniel@purplehaze:/tmp/test$ cat mymodule
print "woho!"
daniel@purplehaze:/tmp/test$ cat test.py 
import imp
imp.load_source("apanapansson", "mymodule")
daniel@purplehaze:/tmp/test$ python test.py
woho!
daniel@purplehaze:/tmp/test$ 
like image 119
dsvensson Avatar answered Jan 11 '23 09:01

dsvensson