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

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

问题描述

在我开发的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扩展名。所以,为了测试框架仍然能够导入模块,我必须做这个象征性的链接thingie:

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

是否可以导入Python中的一个文件名,或者你能想到一个更优雅的解决方案吗?

解决方案

你最有可能使用一些通过使用导入钩子来诡计,我不会推荐它。另一方面,我也可能会这样做,另一方面,将.py脚本放在某个地方,并使'.py'与.py文件的符号链接。所以你的库可以是任何地方,你可以通过导入它来正常运行测试(因为它有py扩展名),然后/ usr / bin / yetanotherfeature指向它,所以你可以运行它没有py。 p>

编辑:不要这个(至少是钩子部分),import imp解决方案对我来说非常好:)


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天全站免登陆