导入没有 .py 扩展名的 python 模块 [英] Import a python module without the .py extension

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

问题描述

我有一个名为 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.

import imp
foobar = imp.load_source('foobar', '/path/to/foobar')

这个SO 讨论还展示了一些有趣的选项.

This SO discussion also shows some interesting options.

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

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