导入没有.py扩展名的python模块 [英] Import a python module without the .py extension
问题描述
我有一个名为foobar的文件(没有.py扩展名)。在同一目录中,我有另一个试图导入它的python文件:
I have a file called foobar (without .py extension). In the same directory I have another python file that tries to import it:
import foobar
但这只有在我将文件重命名为foobar.py时才有效。是否可以导入没有.py扩展名的python模块?
But this only works if I rename the file to foobar.py. Is it possible to import a python module that doesn't have the .py extension?
更新:文件没有扩展名,因为我也将它用作独立脚本,我不想键入.py扩展名来运行它。
Update: the file has no extension because I also use it as a standalone script, and I don't want to type the .py extension to run it.
Update2:我会选择下面提到的符号链接解决方案。
Update2: I will go for the symlink solution mentioned below.
推荐答案
您可以使用 imp.load_source
函数(来自 imp
模块)从一个动态加载模块给定文件系统路径。
You can use the imp.load_source
function (from the imp
module), to load a module dynamically from a given file-system path.
foobar = imp.load_source('foobar', '/path/to/foobar')
这 SO讨论也显示了一些有趣的选项。
This SO discussion also shows some interesting options.
这篇关于导入没有.py扩展名的python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!