Re: [Pyparsing] DSL using pyparsing
Brought to you by:
ptmcg
From: Asim M. <as...@ho...> - 2009-06-12 11:31:29
|
So is there a way for the import hook to somehow inject the import statements, when executing the code? Or does my generated code have to explicitly declare each import statement? Let me try an break it down, suppose i have this code in a file 'Colors.py', the path of which is (xxx.dsl.Colors.py) and for now the Color class resides here but it could be imported from some other external module: import imputil class Color(object): def __init__(self, r, g, b): self.r = r self.g = g self.b = b def __str__(self): return 'cols' def convert_dsl(filepath, fileinfo, filename): srcfile = open(filepath, 'r') data = srcfile.read() srcfile.close() generated_code = '%s' % data print generated_code COMPILE_MODE = 'exec' codeobj = compile(generated_code.rstrip(" \t"), filepath, COMPILE_MODE) return 0, codeobj, {} importer = imputil.ImportManager() importer.add_suffix('.col', convert_dsl) importer.install() --- Is this all that needs to be done or do i have to add some namespace or something? Then i have my abc.col file: c = Color(255, 0, 255) In reality this would be a file which has the dsl that would be py-parsed, so obviously i don't want an import statement in this. If i did add 'from Colors import Color' at the top it works, but in reality i am expecting 'from xxx.dsl.Colors import Color' Now if i run this, i get: from xxx.dsl.Colors import * import abc print abc.c I get the error: c = Color(255, 0, 255) NameError: name 'Color' is not defined. I am not quite sure where the imports should be defined or resolved from. > From: pt...@au... > To: as...@ho...; pyp...@li... > Subject: RE: [Pyparsing] DSL using pyparsing > Date: Thu, 11 Jun 2009 21:11:56 -0500 > > > Thanks Paul, I think i have the idea now. I am using Imputil, so the > > problem i have now is that i am using imputil, so when say i am trying to > > compile a script, say: > > > > A = Color(100, 10, 50) > > > > I get a "NameError: name 'Color' is not defined". Any ideas? > > > > > > Well, you *are* generating Python code, so if you had originally written > that line of code you would get the same error. The Color class needs to > come from somewhere. Either import it from another module, or define it > somewhere in your source program (maybe in the module you import to include > the imputil hook). > > -- Paul > > |