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

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

问题描述

如何在 Python 3.4 中加载 Python 模块的完整路径?

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

一个类似的问题 如何导入一个给定完整的模块path? 涵盖 3.4 之前的 Python 版本,但结论是 Python 3.4 中的支持已被弃用,因此不推荐使用 Python 3.4 的任何解决方案.

A similar question How to import a module given the full path? covers Python versions before 3.4, but the conclusion is that support in Python 3.4 is deprecated for the presented answers, so any solution for Python 3.4 is appreciated.

注意这个问题不是导入abitrary python源的重复文件.(Python 3.3+),因为对此的答案也使用 loader.load_module(),它在 Python 3.4 中已弃用,如 答案,详细信息在考虑离开 importlib.abc.Loader.load_module(),以及 importlib.

Note that this question is not a duplicate of Import abitrary python source file. (Python 3.3+), since answers for this also use loader.load_module() which is deprecated in Python 3.4, as said in answer, with details in Consider leaving importlib.abc.Loader.load_module(), and documentation in importlib.

因此需要在 Python 3.4 中支持通过完整路径导入模块的解决方案.

So a supported solution for module import by full path in Python 3.4 is needed.

推荐答案

这应该适用于所有 python 文件,无论文件扩展名如何:

This should work for all python files, regardless of file extension:

import importlib.machinery

modulename = importlib.machinery.SourceFileLoader('modulename','/Path/To/module.py').load_module()

imp.load_module 的弃用消息中提到了此方法 文档.

This method was mentioned in the deprecation message in the imp.load_module documentation.

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

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