本文共 2713 字,大约阅读时间需要 9 分钟。
python包的运行方式有多种:
python pkg_name 以文件夹运行包
python -m pkg_name 以模块方式运行包
python python_file_name.py
三种方式统一
在包路径MyTools/import_pkg/__init__.py, 内容如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
文件名: __init__.py
功 能:报的初始化
版权信息:版本所有(C) 2019-2022
修改记录:
2021-01-18 22:12:22 创建
2021-01-18 22:12:22 修改
"""
__all__ = ["main_run"]
def __dir__():
return __all__
def main_run():
"""主函数"""
print("Hello Package Run Main Function")
if __name__ == "__main__":
main_run()
在包路径MyTools/import_pkg/__main__.py, 内容如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
文件名: __main__.py
功 能:ImportTopPkg类,该类主要涉及顶级包的自动导入,并执行main函数功能
版权信息:版本所有(C) 2019-2022
修改记录:
2021-01-18 22:12:42 创建
2021-01-18 22:12:42 修改
"""
import os
import sys
from types import FunctionType
from typing import Optional
from importlib.machinery import PathFinder
from importlib import import_module
# noinspection PyTypeChecker
class ImportTopPkg:
"""导入顶级包"""
class SelfModuleMetaFinder(PathFinder):
"""导入自定义模块的源查找类"""
def __init__(self, pkg_path: Optional[str] = None):
self._pkg_path = dict()
if pkg_path is None:
return
self.add_pkg_path(pkg_path)
def add_pkg_path(self, pkg_path: str):
if not pkg_path:
return ""
pkg_path = os.path.realpath(pkg_path)
pkg_name = os.path.basename(pkg_path).split(os.path.extsep)[0]
pkg_path = os.path.dirname(pkg_path)
self._pkg_path[pkg_name] = pkg_path
return pkg_name
def find_spec(self, fullname, path=None, target=None):
if path is None:
path = tuple(self._pkg_path.values())
return super().find_spec(fullname, path, target)
def get_pkg_path(self):
return self._pkg_path
@classmethod
def register_meta_path(cls):
for finder in sys.meta_path:
if isinstance(finder, cls.SelfModuleMetaFinder):
return finder
finder = cls.SelfModuleMetaFinder()
sys.meta_path.append(finder)
return finder
@classmethod
def add_pkg_path(cls, pkg_path: Optional[str] = None):
if not pkg_path:
pkg_path = os.path.dirname(__file__)
finder = cls.register_meta_path()
pkg_name = finder.add_pkg_path(pkg_path)
return pkg_name
@classmethod
def import_lib(cls, pkg_name: str):
module = import_module(pkg_name)
sys.modules.setdefault(pkg_name, module)
return module
@classmethod
def imp_parent_pkg(cls):
cls.register_meta_path()
pkg_name = cls.add_pkg_path()
return cls.import_lib(pkg_name)
@classmethod
def exec_self_pkg(cls):
module = cls.imp_parent_pkg()
for attr_name in dir(module):
attr_value = getattr(module, attr_name)
if not isinstance(attr_value, FunctionType):
continue
if attr_name.startswith("main") or attr_name.startswith("__main"):
attr_value()
def main_run():
"""主函数"""
ImportTopPkg.exec_self_pkg()
if __name__ == "__main__":
main_run()
运行方式:
python import_pkg
python -m import_pkg
python -m .\import_pkg\__main__.py
参考资料
(c) 著作权归作者所有
转载地址:http://gtowx.baihongyu.com/