在我开发的Python系统中,我们通常有这种模块结构。
mymodule/
mymodule/mymodule/feature.py
mymodule/test/feature.py
这使得我们的小测试框架可以轻松导入 test/feature.py 并运行单元测试。然而,我们现在需要一些 shell 脚本(用 Python 编写):
mymodule/
mymodule/scripts/yetanotherfeature.py
mymodule/test/yetanotherfeature.py
Yetanotherfeature.py 由 Debian 软件包模块安装到 /usr/bin 中。但我们显然不想要 .py 扩展名。因此,为了使测试框架仍然能够导入模块,我必须执行此符号链接操作:
mymodule/
mymodule/scripts/yetanotherfeature
mymodule/scripts/yetanotherfeature.py @ -> mymodule/scripts/yetanotherfeature
mymodule/test/yetanotherfeature.py
是否可以在Python中按文件名导入模块,或者你能为此想到一个更优雅的解决方案吗?
The 小鬼模块 http://docs.python.org/library/imp.html用于此:
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$
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)