From: Ype K. <yk...@xs...> - 2001-09-22 13:02:40
|
Frank, >If anyone will confirm this is the best way to use exec and globals, I would >certain appreciate your feedback. > >The goal is to have the Jython equivalent of server-side include files where >one script calls another and can share variables. In an experiment I created >two files: > >exec_example.py > >def makethecall: > i=100 > exec open("included.py").read() > print "j=", j >makethecall() > > >included.py > >j=101 >print "i=", i > >By running exec_example I see: > >i=100 >j=101 > >Is this the best way to have scripts calling other scripts and returning >results? This illustrates that the global namespace passed to exec is the local namespace of the makethecall function. You can have more control over the namespaces passed to exec by passing these as arguments, too. My guess is that you are going to need this. In this particular example I think I'd prefer to use execfile(), but that is rather minor. You could also note that: - the __name__ variable in the executed code will have the value of the __name__ variable at the exec call, which might not be desirable. - the function makethecall is defined when included.py is exec'ed, There are a few other things that are normally provided by jython itself for the code it executes that you might want to consider: In case you want to control import's in exec'ed code: - sys.modules might change during the exec when the executed code imports other modules. - neither exec nor execfile does any module administration in sys.modules. You can do this yourself by (temporarily) adding a new.module() to sys.modules. In case you want more control over imports in executed code you'll need to control sys.path too, as it determines the places from which modules can be loaded. The exec'ed code might throw - a jython exception. You might want to catch it. - a java exception that you cannot catch in jython. The exec'ed code might not return. This is rather hard to control, but it is possible in jython by using a (deprecated) java call to stop the thread doing the exec. Fortunately the python language does not encourage writing endless loops. The nice thing about python/jython is that you can control almost all of these aspects when using exec or execfile. The downside is off course that you might have to write the code to do some of this. If you'd like to see an example, let me know. Regards, Ype |