自定义基于python的DSL中异常的回溯

2024-10-01 17:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建一个基于python的DSL只是为了好玩。现在,它只是将文本编译成直接执行python代码的AST。我是说如果我写:

a = int(read("input something: "))
b = a**2

它将其转化为如下树:

^{pr2}$

每个节点都将使用如下代码执行:

class VariableSet(object):
    def __init__(self, name, expr):
        self.name = name
        self.expr = expr

    def __call__(self, scope):
        value = self.expr(scope)
        scope.put(self.name, value)
        return value

它确实很管用。我希望在某些指令抛出异常时,异常堆栈回溯指向DSL源代码,而不是python AST代码。现在,我只看到:

Traceback (most recent call last):
  File "parser.py", line 164, in <module>
    parse(data)(scope)  
  File "/home/juanplopes/Projects/my-parser/ast.py", line 158, in __call__
    result = expr(scope)
  File "/home/juanplopes/Projects/my-parser/ast.py", line 63, in __call__
    value = self.expr(scope)
  File "/home/juanplopes/Projects/my-parser/ast.py", line 81, in __call__
    return self.method(scope)(*[arg(scope) for arg in self.args])
  File "/home/juanplopes/Projects/my-parser/ast.py", line 81, in __call__
    return self.method(scope)(*[arg(scope) for arg in self.args])
  File "parser.py", line 153, in read
    raise Exception('some exception')
Exception: some exception

有没有一种方法可以定制在python中如何生成回溯?在


Tags: nameinpyselfparserhomevaluemy

热门问题