我正在用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()
保存为函数的属性来保存和重用locals()
,这只是一种方法,YMMV。你知道吗相关问题 更多 >
编程相关推荐