安全执行 matplotlib 代码并保存图表。 参数 ---- code : str 要执行的 matplotlib Python 代码 output_path : str | Path 图表输出路径(包含文件名,如 /tmp/chart.png) timeout : int, default 30 执行超时时间(秒) allowed_modules : List[str], optional 允许导入的模块列表,默认为 ["matplotlib", "numpy",
(
code: str,
output_path: Union[str, Path],
timeout: int = 30,
allowed_modules: Optional[List[str]] = None,
)
| 1226 | |
| 1227 | |
| 1228 | def execute_matplotlib_code( |
| 1229 | code: str, |
| 1230 | output_path: Union[str, Path], |
| 1231 | timeout: int = 30, |
| 1232 | allowed_modules: Optional[List[str]] = None, |
| 1233 | ) -> Dict[str, Any]: |
| 1234 | """ |
| 1235 | 安全执行 matplotlib 代码并保存图表。 |
| 1236 | |
| 1237 | 参数 |
| 1238 | ---- |
| 1239 | code : str |
| 1240 | 要执行的 matplotlib Python 代码 |
| 1241 | output_path : str | Path |
| 1242 | 图表输出路径(包含文件名,如 /tmp/chart.png) |
| 1243 | timeout : int, default 30 |
| 1244 | 执行超时时间(秒) |
| 1245 | allowed_modules : List[str], optional |
| 1246 | 允许导入的模块列表,默认为 ["matplotlib", "numpy", "pandas"] |
| 1247 | |
| 1248 | 返回 |
| 1249 | ---- |
| 1250 | Dict[str, Any] |
| 1251 | { |
| 1252 | "success": bool, |
| 1253 | "output_path": str, # 成功时返回图片路径 |
| 1254 | "error": str, # 失败时返回错误信息 |
| 1255 | } |
| 1256 | """ |
| 1257 | import subprocess |
| 1258 | import tempfile |
| 1259 | |
| 1260 | if allowed_modules is None: |
| 1261 | allowed_modules = ["matplotlib", "numpy", "pandas", "math"] |
| 1262 | |
| 1263 | output_path = Path(output_path) |
| 1264 | output_path.parent.mkdir(parents=True, exist_ok=True) |
| 1265 | |
| 1266 | # 安全性检查:禁止危险操作 |
| 1267 | dangerous_patterns = [ |
| 1268 | r'\bos\.system\b', |
| 1269 | r'\bsubprocess\b', |
| 1270 | r'\beval\b', |
| 1271 | r'\bexec\b', |
| 1272 | r'\bopen\s*\(', |
| 1273 | r'\b__import__\b', |
| 1274 | r'\bimport\s+os\b', |
| 1275 | r'\bimport\s+sys\b', |
| 1276 | r'\bimport\s+subprocess\b', |
| 1277 | r'\bfrom\s+os\b', |
| 1278 | r'\bfrom\s+sys\b', |
| 1279 | ] |
| 1280 | |
| 1281 | for pattern in dangerous_patterns: |
| 1282 | if re.search(pattern, code): |
| 1283 | return { |
| 1284 | "success": False, |
| 1285 | "output_path": "", |
no test coverage detected