execfile('comp1.py')
def exefi(name, locals=None, globals=None):
exec compile(open(name).read(), name, 'exec') in locals, globals
exefi('comp1.py')
it can execute successfully. but
#execfile('comp1.py')
def exefi(name, locals=None, globals=None):
exec compile(open(name).read(), name, 'exec') in locals, globals
exefi('comp1.py')
it come with
"File "comp1.py", line 39, in <module>
ex=c.end()
File "comp1.py", line 17, in end
return compile(string.join(self.code, "\n"),"<code>","exec")
NameError: global name 'string' is not defined"
why?
and the comp1.py is
import sys, string
class CoGen:
def begin(self, tab='\t'):
self.code=[]
self.tab=tab
self.level=0
def end(self):
self.code.append('')
return compile(string.join(self.code, "\n"),"<code>","exec")
def write(self, string):
self.code.append(self.tab*self.level+string)
def indent(self):
self.level+=1
def dedent(self):
if self.level == 0:
raise SyntaxError, "internal error in code generator"
self.level-= 1
c= CoGen()
c.begin()
c.write("for i in range(5):")
c.indent()
c.write("print 'int code generator!'")
c.dedent()
ex=c.end()
exec ex
print ex