如何在给定完整路径的情况下导入模块? [英] How to import a module given the full path?

查看:39
本文介绍了如何在给定完整路径的情况下导入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在给定完整路径的情况下加载 Python 模块?

How can I load a Python module given its full path?

请注意,该文件可以位于文件系统中的任何位置,因为它是一个配置选项.

Note that the file can be anywhere in the filesystem, as it is a configuration option.

推荐答案

对于 Python 3.5+ 使用:

For Python 3.5+ use:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

对于 Python 3.3 和 3.4 使用:

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

(虽然这在 Python 3.4 中已被弃用.)

(Although this has been deprecated in Python 3.4.)

对于 Python 2 使用:

For Python 2 use:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

对于已编译的 Python 文件和 DLL,有等效的便利函数.

There are equivalent convenience functions for compiled Python files and DLLs.

另见http://bugs.python.org/issue21436.

这篇关于如何在给定完整路径的情况下导入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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