在我开发的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中通过文件名导入模块,或者您能想到更优雅的解决方案吗?
该小鬼模块用于此:
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)