如何导入具有绝对路径的模块并将参数传递给该模块,以便被调用的模块可以实际在其内部使用该变量?绝对路径是指这样的"/home/example.com/directory/file.py"
。我将此模块名称作为实际脚本的命令行参数的一部分。在该脚本中,我必须导入file.py
并将某些参数传递给它们。
防爆码:
filename = '/home/example.com/directories/file.py'
path = re.split(filename, script_path, maxsplit=1)[0]
print(path) --> /home/example.py/directories/
module_name = filename.rstrip('.py')
print(module_name) --> file.py
spec = importlib.util.spec_from_file_location(module_name, path)
module = importlib.util.module_from_spec(spec)
print(type(module))
# filepath = re.sub('/','.',script_path)
# print(filepath)
# module = importlib.import_module(script_path)
module.testvars = [r_config, t_config]
# spec.loader.exec_module(module)
alltest = unittest.TestSuite()
alltest.addTest(unittest.findTestCases(module))
runner = unittest.TextTestRunner()
但是此代码出现以下错误:
Traceback (most recent call last): module = importlib.util.module_from_spec(spec)
File "<frozen importlib._bootstrap>", line 568, in module_from_spec
AttributeError: 'NoneType' object has no attribute 'loader'