From: Ype K. <yk...@xs...> - 2002-02-01 12:14:35
|
Matt, >Hi all, > >I have an application which embeds jython, and whenever I run a script, >the __name__ variable is set to '__builtin__' by I assume the >interpreter. >Normally in python, modules can check the value of __name__ to selectively >run code based on being run from the commandline (value of '__main__') vs >being imported. >Whats the best way to do this in jython? >Currently what I do is shown below but I'm not sure if this is correct. >The reason for my apprehension is that when I just run an interactive >interpreter, I notice that sys.modules has a __main__ module, so I'm >wondering if I have to create that or something else special. PyUnit uses the __name__ variable to obtain the namespace of the module it is being called from. So you'll need to add a module with named __name__ if you want to support this. You might want to save an evt. previous module with the same name. In Jython (off the top of my head): mainName = '__main__' if sys.modules.has_key(mainName): oldMod = sys.modules[mainName] else: oldMod = None try: mod = new.module(mainName) sys.modules[mainName] = mod mod.__dict__['__name__'] = mainName execfile('myscript.py', mod.__dict__) finally: if oldMod is not None: sys.modules[mainName] = oldMod else: del sys.modules[mainName] mod = None >Any help appreciated, thanks, I've never done this in java, so you'll have to translate yourself and/or do it all in jython and execfile that. Import the larger part as a function or class for efficiency. You might also want to control sys.path, use a search path for your scripts, and catch exceptions from execfile(). Have fun, Ype -- |