You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求适用于教育游戏的受限Python 3脚本执行引擎方案

Secure Restricted Python Execution Engine for Educational Games

Great question—building a secure, constrained Python runtime for educational games is absolutely achievable, even with Python's tricky sandboxing reputation. Since you only need a small subset of Python (loops, conditionals, and a handful of predefined functions like move()/turn()), you can focus on tight control rather than full sandbox coverage. Here are my top tailored solutions:

1. AST-Based Custom Interpreter (Most Controlled)

Python's ast module lets you parse user code into an Abstract Syntax Tree, which you can inspect, modify, and validate before execution. This is the gold standard for your use case because you can explicitly whitelist only the syntax and functions you want to allow.

How to implement it:

  • Parse the user's code with ast.parse() to get the AST.
  • Traverse the AST using ast.NodeVisitor or ast.NodeTransformer to reject any nodes outside your whitelist (e.g., disallow imports, class definitions, attribute access except for your predefined functions, or calls to non-whitelisted functions).
  • For allowed nodes (like If, For, While, and Call to move()/turn()), you can either:
    1. Execute the nodes directly by writing a custom evaluator, or
    2. Modify the AST to remove risky elements, then compile and run it in a restricted global environment.

Example snippet for AST validation:

import ast

class SafeASTValidator(ast.NodeVisitor):
    allowed_nodes = {
        ast.Module, ast.Expr, ast.If, ast.For, ast.While,
        ast.Pass, ast.Call, ast.Name, ast.Load, ast.Constant
    }
    allowed_functions = {'move', 'turn'}

    def visit_Call(self, node):
        if isinstance(node.func, ast.Name) and node.func.id not in self.allowed_functions:
            raise ValueError(f"Calling function '{node.func.id}' is not allowed")
        self.generic_visit(node)

    def generic_visit(self, node):
        if type(node) not in self.allowed_nodes:
            raise ValueError(f"Syntax '{type(node).__name__}' is not allowed")
        super().generic_visit(node)

# Validate user code
user_code = "move()\nturn()\nfor i in range(3): move()"
tree = ast.parse(user_code)
validator = SafeASTValidator()
validator.visit(tree)

# Compile and run in restricted globals
safe_globals = {
    'move': lambda: print("Moving..."),
    'turn': lambda: print("Turning..."),
    '__builtins__': {'range': range, 'True': True, 'False': False, 'None': None}
}
exec(compile(tree, filename='<user_code>', mode='exec'), safe_globals)

Pros:

  • Complete control over allowed syntax and behavior
  • Minimal risk of sandbox escape if validation is thorough
  • Easy to extend if you need to add more functions later

Cons:

  • Requires writing and maintaining AST validation logic
  • Takes more initial setup than simpler approaches

2. Restricted Execution with exec() + Locked-Down Globals

If you want a quicker solution, you can use Python's built-in exec() function with a strictly controlled global environment. The key is to strip out all unnecessary built-ins and only expose your predefined functions.

How to implement it:

  • Create a safe_globals dictionary that includes only:
    • A minimal subset of __builtins__ (e.g., True, False, None, range if needed)
    • Your move() and turn() functions
  • Pass this dictionary to exec() as the global namespace, leaving locals empty or similarly restricted.

Important note: Always combine this with AST validation (from option 1) to block risky syntax (like imports or attribute access to dangerous objects). Without AST checks, clever users could still find ways to escape the global lock.

Pros:

  • Fast to implement
  • Leverages Python's native execution engine

Cons:

  • Risk of sandbox escape if globals aren't properly locked down (even with careful setup)
  • Less control over allowed syntax compared to AST validation

3. Use RestrictedPython Library

RestrictedPython is a mature library designed specifically for running untrusted Python code in a safe environment. It modifies Python's bytecode to restrict access to attributes, functions, and modules, and lets you define fine-grained policies for what's allowed.

How to implement it:

  • Install RestrictedPython via pip
  • Define a "policy" that allows only your predefined functions and basic control flow syntax
  • Compile the user code using RestrictedPython's utilities, then execute it in the restricted environment

Pros:

  • Battle-tested for security
  • Handles many edge cases you might miss with a custom solution
  • Supports more Python features if you need to expand later

Cons:

  • Has a learning curve to configure policies correctly
  • Might be overkill for your minimal subset needs

4. Build a Custom DSL (Domain-Specific Language)

If your allowed syntax is extremely limited (only loops, conditionals, and move()/turn()), you could skip Python entirely and build a tiny custom DSL. This gives you absolute control over every part of the language, with zero risk of sandbox escape.

How to implement it:

  • Define a simple grammar for your language (e.g., move(); turn(); repeat 3 times: move(); if facing north: turn())
  • Write a parser (using tools like pyparsing or even a hand-written recursive descent parser) to convert user code into an executable structure
  • Execute the parsed structure using your own interpreter logic

Pros:

  • 100% control over allowed operations
  • No sandboxing vulnerabilities
  • Error messages can be tailored specifically for your educational game's context

Cons:

  • Requires building a full parser and interpreter from scratch
  • Not as flexible if you want to add more Python-like features later

Final Recommendation

For your educational game use case, I'd start with the AST validation + restricted exec() combo. It strikes the best balance between security, control, and development effort. If you find yourself needing more robust sandboxing later, you can transition to RestrictedPython. If you want to create a truly tailored learning experience with simplified syntax, a custom DSL is a great long-term option.

内容的提问来源于stack exchange,提问作者Rodion Gorkovenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:00:21