|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 | # -*- coding: utf-8 -*- |
| 3 | +import asyncio |
3 | 4 | import inspect |
4 | 5 | import os |
| 6 | +import subprocess |
| 7 | +import sys |
5 | 8 | import warnings |
6 | 9 |
|
| 10 | +from asyncio import subprocess as async_subprocess |
| 11 | + |
7 | 12 | import rtoml |
8 | 13 |
|
9 | 14 | from fastapi import APIRouter |
@@ -119,3 +124,42 @@ def plugin_router_inject() -> None: |
119 | 124 |
|
120 | 125 | # 将插件路由注入到目标 router 中 |
121 | 126 | target_router.include_router(plugin_router) |
| 127 | + |
| 128 | + |
| 129 | +def install_requirements() -> None: |
| 130 | + """安装插件依赖""" |
| 131 | + plugins = get_plugins() |
| 132 | + for plugin in plugins: |
| 133 | + requirements_file = os.path.join(PLUGIN_DIR, plugin, 'requirements.txt') |
| 134 | + if not os.path.exists(requirements_file): |
| 135 | + continue |
| 136 | + else: |
| 137 | + try: |
| 138 | + subprocess.run([sys.executable, '-m', 'ensurepip', '--upgrade']) |
| 139 | + subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', requirements_file]) |
| 140 | + except subprocess.CalledProcessError as e: |
| 141 | + raise EnvironmentError(f'插件 {plugin} 依赖安装失败:{e}') from e |
| 142 | + |
| 143 | + |
| 144 | +async def install_requirements_async() -> None: |
| 145 | + """异步安装插件依赖""" |
| 146 | + plugins = get_plugins() |
| 147 | + for plugin in plugins: |
| 148 | + requirements_file = os.path.join(PLUGIN_DIR, plugin, 'requirements.txt') |
| 149 | + if not os.path.exists(requirements_file): |
| 150 | + continue |
| 151 | + else: |
| 152 | + await async_subprocess.create_subprocess_exec(sys.executable, '-m', 'ensurepip', '--upgrade') |
| 153 | + res = await async_subprocess.create_subprocess_exec( |
| 154 | + sys.executable, |
| 155 | + '-m', |
| 156 | + 'pip', |
| 157 | + 'install', |
| 158 | + '-r', |
| 159 | + requirements_file, |
| 160 | + stdout=asyncio.subprocess.PIPE, |
| 161 | + stderr=asyncio.subprocess.PIPE, |
| 162 | + ) |
| 163 | + _, stderr = await res.communicate() |
| 164 | + if res.returncode != 0: |
| 165 | + raise EnvironmentError(f'插件 {plugin} 依赖包安装失败:{stderr}') |
0 commit comments