Python导入:导入没有.py扩展名的模块?

poj*_*ojo 3 python debian

在我开发的Python系统中,我们通常有这个模块结构.

mymodule/
mymodule/mymodule/feature.py
mymodule/test/feature.py
Run Code Online (Sandbox Code Playgroud)

这允许我们的小测试框架轻松导入test/feature.py并运行单元测试.但是,我们现在需要一些shell脚本(用Python编写):

mymodule/
mymodule/scripts/yetanotherfeature.py
mymodule/test/yetanotherfeature.py
Run Code Online (Sandbox Code Playgroud)

yetanotherfeature.py由模块Debian软件包安装到/ usr/bin中.但我们显然不希望扩展.py扩展.所以,为了使测试框架仍然能够导入模块,我必须做这个符号链接的东西:

mymodule/
mymodule/scripts/yetanotherfeature
mymodule/scripts/yetanotherfeature.py @ -> mymodule/scripts/yetanotherfeature
mymodule/test/yetanotherfeature.py
Run Code Online (Sandbox Code Playgroud)

是否可以在Python中通过文件名导入模块,或者您能想到更优雅的解决方案吗?

dsv*_*son 9

小鬼模块用于此:

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$ 
Run Code Online (Sandbox Code Playgroud)

  • 这将创建一个名为"mymodulec"的文件.它应该是.pyc,但由于原始文件没有以.py结尾,所以它只是在最后添加ac.这看起来很怪异.我可以不这样做吗? (3认同)