导入非python文件
import-x的Python项目详细描述
一个ext-tensible加载程序,可以导入类似于python模块的任何内容。
支持python3.6+。
用法
路径中的示例json文件foo.json:
{"why":"not",}
# Extend the ExtensionLoader and implement 'handle_module' method# where you will get a module object and the path to that module.>>>fromimport_ximportExtensionLoader>>>classJsonLoader(ExtensionLoader):extension='.json'auto_enable=False@staticmethoddefhandle_module(module,path):""" Load the json file and set as `data` attribute of the module. """json_file=Path(path)content=json_file.read_text()try:data=json.loads(content)except(json.JSONDecodeError,ValueError):data={}module.data=data>>>json_imports=JsonLoader()>>>withjson_imports:importfoo>>>foo.data>>>{"why":"not"}
如果要在没有上下文管理器的情况下自动启用导入,则只需 在加载程序中执行auto_enable = True。