test-df-demt / pyc_loader.py
luckiness's picture
Upload 10 files
be7f12e verified
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pyc文件加载器
import sys
import os
import importlib.util
# 确保当前目录在Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.insert(0, current_dir)
def load_pyc(pyc_file):
# 加载一个.pyc文件
if not os.path.exists(pyc_file):
print(f"错误: 文件 {pyc_file} 不存在")
return None
try:
module_name = os.path.splitext(os.path.basename(pyc_file))[0]
spec = importlib.util.spec_from_file_location(module_name, pyc_file)
if spec is None:
print(f"错误: 无法为 {pyc_file} 创建规范")
return None
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
return module
except Exception as e:
print(f"加载 {pyc_file} 失败: {e}")
return None
def main():
# 命令行入口点
if len(sys.argv) < 2:
print("用法: python pyc_loader.py <pyc文件> [函数名]")
return 1
pyc_file = sys.argv[1]
function_name = sys.argv[2] if len(sys.argv) > 2 else "main"
module = load_pyc(pyc_file)
if not module:
return 1
if hasattr(module, function_name):
func = getattr(module, function_name)
if callable(func):
return func()
else:
print(f"错误: {function_name} 不是一个可调用函数")
return 1
else:
print(f"错误: 模块中没有 {function_name} 函数")
return 1
if __name__ == "__main__":
sys.exit(main())