Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
boleyn opened this issue Aug 21, 2024 · 4 comments
Open

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

boleyn opened this issue Aug 21, 2024 · 4 comments

Comments

@boleyn
Copy link

boleyn commented Aug 21, 2024

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
Copy link
Author

boleyn commented Aug 21, 2024

这样,缺失的依赖只有第一次执行比较慢,后面就会变快

@leezhuuuuu
Copy link
Owner

这个方案安装库只是临时的,每次容器重启环境就会重置

@leezhuuuuu
Copy link
Owner

不过这个方案可以采纳,临时性自动解决依赖问题

@Genuifx
Copy link

Genuifx commented Sep 30, 2024

是不是可以考虑把依赖维护起来,每次安装下

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants