将源代码字符串转换为函数,支持 inspect.getsource
(source_code: str, func_name: str)
| 624 | else f'{image_base64}' |
| 625 | ) |
| 626 | def source_to_function(source_code: str, func_name: str): |
| 627 | """将源代码字符串转换为函数,支持 inspect.getsource""" |
| 628 | # 创建临时文件 |
| 629 | with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f: |
| 630 | f.write(source_code) |
| 631 | temp_path = f.name |
| 632 | |
| 633 | try: |
| 634 | # 导入临时模块 |
| 635 | import importlib.util |
| 636 | spec = importlib.util.spec_from_file_location("temp_module", temp_path) |
| 637 | module = importlib.util.module_from_spec(spec) |
| 638 | spec.loader.exec_module(module) |
| 639 | |
| 640 | # 获取函数 |
| 641 | func = getattr(module, func_name) |
| 642 | return func |
| 643 | |
| 644 | finally: |
| 645 | # 清理临时文件 |
| 646 | os.unlink(temp_path) |
| 647 | |
| 648 | |
| 649 |
nothing calls this directly
no outgoing calls
no test coverage detected