Python 使用正则表达式设置变量

Python 使用正则表达式设置变量,python,regex,Python,Regex,我正在使用regex创建一种语言这是我迄今为止的代码: import re outputf=r'output (.*)' inputf=r'(.*) = input (.*)' intf=r'int (.*) = (\d)' floatf=r'float (.*) = (\d\.\d)' def check_line(line): outputq=re.match(outputf, line) if output

我正在使用regex创建一种语言这是我迄今为止的代码:

    import re

    outputf=r'output (.*)'
    inputf=r'(.*) = input (.*)'
    intf=r'int (.*) = (\d)'
    floatf=r'float (.*) = (\d\.\d)'

    def check_line(line):
        outputq=re.match(outputf, line)
        if outputq:
            exec ("print (%s)" % outputq.group(1))

        inputq=re.match(inputf, line)
        if inputq:
            exec ("%s=raw_input(%s)"%(inputq.group(1), inputq.group(2)))

        intq=re.match(intf, line)
        if intq:
            exec ("%s = %s"%(intq.group(1), intq.group(2)))
            print x

        floatq=re.match(floatf, line)
        if floatq:
            exec ("%s = %s"%(floatq.group(1), floatq.group(2)))


    code=open("code.psu", "r").readlines()

    for line in code:
        check_line(line) 
所以它工作得很好,但在我的文件中,以下是我的代码:

int x = 1
output "hi"
float y = 1.3
output x
但是当我读到第4行时,它说变量x没有定义。如何设置它以便它也可以打印变量?

当调用exec()时,它可以选择性地传递它将使用的全局和局部变量字典。默认情况下,它使用
globals()
locals()

问题是,在您的示例中,您正在使用
exec()
设置一个变量,如
x=1
。这确实得到了设置,您可以在
locals()
中看到它。但是在你离开函数之后,这个变量就消失了

因此,您需要在每次调用
exec()
之后保存
locals()

编辑:

我写这篇补遗是因为你自己回答了,所以我想我还是把它贴出来

下面是一个失败的简单示例(错误与您的示例相同):

这里有一个修改过的版本,它保存并重用
locals()
,方法是将它们保存为函数的属性-这只是一种方法,YMMV

def locals_saved(firsttime):
    if not hasattr(locals_saved, "locals"):
        locals_saved.locals = locals()

    if firsttime:
        exec("x = 1", globals(), locals_saved.locals)
    else:
        exec("print(x)", globals(), locals_saved.locals)

locals_saved(True)
locals_saved(False)

或者您可以执行以下操作:exec(“全局%s;%s=%s”%(floatq.group(1)、floatq.group(1)、floatq.group(2))@AaronGill-Braun-nope,
global
只能在函数内部使用
def locals_saved(firsttime):
    if not hasattr(locals_saved, "locals"):
        locals_saved.locals = locals()

    if firsttime:
        exec("x = 1", globals(), locals_saved.locals)
    else:
        exec("print(x)", globals(), locals_saved.locals)

locals_saved(True)
locals_saved(False)