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

Recommended Answers

All 2 Replies

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")

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.