Code-Interpreter-Api icon indicating copy to clipboard operation
Code-Interpreter-Api copied to clipboard

当代码执行缺少依赖可以这样处理

Open boleyn opened this issue 6 months ago • 4 comments

def run_code(language, code, variables, timeout):
    try:
        if language == 'python':
            code = extract_code(code)
            var_definitions = '\n'.join(f"{key} = {value}" for key, value in variables.items())
            code_with_vars = f"{var_definitions}\n{code}"

            # 将代码包裹在一个try-except块中,以捕获缺少依赖时的 ImportError
            indented_code = '\n'.join(f"    {line}" for line in code_with_vars.splitlines())
            wrapper_code = f"""
def install_package(package):
    import subprocess
    import sys
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package,"-i","https://pypi.tuna.tsinghua.edu.cn/simple"])
    except subprocess.CalledProcessError as e:
        raise ImportError(f"Failed to install package {{package}}. Error: {{str(e)}}")
                    
try:
    {indented_code}
except ImportError as e:
    package_name = str(e).split("'")[1]
    print(f"Attempting to install missing package: {{package_name}}")
    install_package(package_name)
    exec({repr(code_with_vars)}) 
"""

            # 使用subprocess运行代码
            result = subprocess.run([sys.executable, '-c', wrapper_code], capture_output=True, text=True,
                                    timeout=timeout)
            return result.stdout, result.stderr
        else:
            return None, "Unsupported language"
    except subprocess.TimeoutExpired:
        return None, "Code execution timed out"
    except Exception as e:
        return None, str(e)

boleyn avatar Aug 21 '24 08:08 boleyn