首页 > 解决方案 > 给定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

标签: pythonpython-3.x

解决方案


试试这个(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()

推荐阅读