0


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
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by singlem1905
1

First of all don't use "globals" or "locals" as your identifiers, they are built-in functions.

One possibility to fix this is to do this:

#execfile('comp1.py')
def exefi(name, globalsmap=None, localsmap=None):
    if localsmap or globalsmap:
        exec compile(open(name).read(), name, 'exec') in globalsmap, localsmap
    else:
        exec compile(open(name).read(), name, 'exec') in globals()
    
exefi('comp1.py')

Another is to eliminate importing the "string" module and using join directly: return compile("\n".join(self.code),"<code>","exec")

Edited by jcao219: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.