Python 导入:导入没有 .py 扩展名的模块? [英] Python imports: importing a module without .py extension?

查看:41
本文介绍了Python 导入:导入没有 .py 扩展名的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

解决方案

You could most likely use some tricker by using import hooks, I wouldn't recommend it though. On the other hand I would also probably do it the other way around , have your .py scripts somewhere, and make '.py'less symbolic links to the .py files. So your library could be anywhere and you can run the test from within by importing it normall (since it has the py extension), and then /usr/bin/yetanotherfeature points to it, so you can run it without the py.

Edit: Nevermind this (at least the hooks part), the import imp solution looks very good to me :)

这篇关于Python 导入:导入没有 .py 扩展名的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆