用regex设置变量

2024-09-30 06:32:58 发布

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

我正在用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没有定义。如何设置它以便它也可以打印变量?你知道吗


Tags: 代码reoutputifmatchlinegroupcode
1条回答
网友
1楼 · 发布于 2024-09-30 06:32:58

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

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

因此,您需要在每次exec()调用之后保存locals()。你知道吗

编辑:

我是在你自己回答的时候写这个附录的,所以我想我还是把它贴出来。。。你知道吗

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

def locals_not_saved(firsttime):
    if firsttime:
        exec("x = 1")
    else:
        exec("print(x)")

locals_not_saved(True)
locals_not_saved(False)

这是一个修改过的版本,它通过将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)

相关问题 更多 >

    热门问题