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

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

问题描述

如何加载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.

推荐答案

/ p>

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使用:

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