网站类软文,郑州做网站优化外包,保健品网站模版,贵州省住房和城乡建设厅网站人事教育栏目录
需求#xff1a;如何将pkg02/test02.py导入pkg01/test01.py中#xff1f;
方法1#xff1a;使用importlib模块动态导入
对于Python 3.5
对于Python 3.3、3.4
对于Python 2
方法2#xff1a;使用runpy模块动态导入
方法3#xff1a;修改sys.path变量 需求如何将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()#codingutf-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)