python - 给定python 3.5中模块的完整路径,如何导入模块?
问题描述
给定完整路径,如何加载 Python 模块?请注意,该文件可以位于文件系统中的任何位置,因为它是一个配置选项。我在 ubutnu 中使用 python 3.5,到目前为止我的代码是:
创建python模块test.py
import sys
sys.path.append("test/lib/")
from tes1 import Client1
from tes2 import Client2
import tes3
解决方案
试试这个(Python 3.5+ 支持这种语法):
import importlib.util
spec = importlib.util.spec_from_file_location("lib.test", "/test/lib/test.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()
推荐阅读
- angular - 角度如何仅将 in-memory-web-api 用于演示帐户
- python - 如何在所有条形图子图上显示 x 轴标签?
- bash - 拆分一个大文件
- rabbitmq - 带有 RabbitMQ 的 Celery 创建了太多队列
- python - 在函数中引用全局变量的问题
- reactjs - React Router v4 编程重定向:重定向到“相同路由”时出现警告
- powerbi - 在 Power BI 中保留原始时间值
- ruby-on-rails - 如何使用 ruby 在浏览器中读取或获取请求有效负载标头
- logstash - 截断/修剪 logstash 配置以易于维护
- ruby-on-rails - 如何安装导轨?