根据Python模块的完整路径import动态导入
目录
需求:如何将pkg02/test02.py导入pkg01/test01.py中?
方法1:使用importlib模块动态导入
对于Python 3.5+
对于Python 3.3、3.4
对于Python 2
方法2:使用runpy模块动态导入
方法3:修改sys.path变量
需求:如何将pkg02/test02.py导入pkg01/test01.py中?
方法1:使用importlib模块动态导入
对于Python 3.5+
## pkg01/test01.py
import importlib.util
spec = importlib.util.spec_from_file_location('test02', '/root/demo/pkg02/test02.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
print(module)
print(module.args)
module.fun()
module.TestA().testa()
## pkg02/test02.py
print('导入demo/pkg02/test02.py')
args = {'a': 100}
def fun():print('func in demo/pkg02/test02.py')
class TestA:def testa(self):print('TestA.testa in demo/pkg02/test02.py')
对于Python 3.3、3.4
## pkg01/test01.py
from importlib.machinery import SourceFileLoader
loader = SourceFileLoader('test02', '/root/demo/pkg02/test02.py')
module = loader.load_module()
print(module)
print(module.args)
module.fun()
module.TestA().testa()
## pkg02/test02.py
print('导入demo/pkg02/test02.py')
args = {'a': 100}
def fun():print('func in demo/pkg02/test02.py')
class TestA:def testa(self):print('TestA.testa in demo/pkg02/test02.py')
对于Python 2
## pkg01/test01.py
import imp
module = imp.load_source('test02', '/root/demo/pkg02/test02.py')
print(module)
print(module.args)
module.fun()
module.TestA().testa()
#coding=utf-8
## pkg02/test02.py
print('导入demo01/pkg02/test02.py')
args = {'a': 100}
def fun():print('func in demo01/pkg02/test02.py')
class TestA:def testa(self):print('TestA.testa in demo01/pkg02/test02.py')
方法2:使用runpy模块动态导入
## pkg01/test01.py
from runpy import run_path
settings = run_path('/root/demo/pkg02/test02.py')
print(settings['args'])
settings['fun']()
settings['TestA']().testa()
## pkg02/test02.py
print('导入demo/pkg02/test02.py')
args = {'a': 100}
def fun():print('func in demo/pkg02/test02.py')
class TestA:def testa(self):print('TestA.testa in demo/pkg02/test02.py')
方法3:修改sys.path变量
## pkg01/test01.py
import sys,os
cur_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(cur_dir))
print(sys.path)
from pkg02 import test02
print(test02)
print(test02.args)
test02.fun()
test02.TestA().testa()
## pkg02/test02.py
print('导入demo/pkg02/test02.py')
args = {'a': 100}
def fun():print('func in demo/pkg02/test02.py')
class TestA:def testa(self):print('TestA.testa in demo/pkg02/test02.py')