Return a new 'main' module object for user code execution. ``filename`` should be the path of the script which will be run in the module. Requests with the same filename will get the same module, with its namespace cleared. ``modname`` should be the
(self, filename, modname)
| 1085 | #------------------------------------------------------------------------- |
| 1086 | |
| 1087 | def new_main_mod(self, filename, modname): |
| 1088 | """Return a new 'main' module object for user code execution. |
| 1089 | |
| 1090 | ``filename`` should be the path of the script which will be run in the |
| 1091 | module. Requests with the same filename will get the same module, with |
| 1092 | its namespace cleared. |
| 1093 | |
| 1094 | ``modname`` should be the module name - normally either '__main__' or |
| 1095 | the basename of the file without the extension. |
| 1096 | |
| 1097 | When scripts are executed via %run, we must keep a reference to their |
| 1098 | __main__ module around so that Python doesn't |
| 1099 | clear it, rendering references to module globals useless. |
| 1100 | |
| 1101 | This method keeps said reference in a private dict, keyed by the |
| 1102 | absolute path of the script. This way, for multiple executions of the |
| 1103 | same script we only keep one copy of the namespace (the last one), |
| 1104 | thus preventing memory leaks from old references while allowing the |
| 1105 | objects from the last execution to be accessible. |
| 1106 | """ |
| 1107 | filename = os.path.abspath(filename) |
| 1108 | try: |
| 1109 | main_mod = self._main_mod_cache[filename] |
| 1110 | except KeyError: |
| 1111 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
| 1112 | modname, |
| 1113 | doc="Module created for script run in IPython") |
| 1114 | else: |
| 1115 | main_mod.__dict__.clear() |
| 1116 | main_mod.__name__ = modname |
| 1117 | |
| 1118 | main_mod.__file__ = filename |
| 1119 | # It seems pydoc (and perhaps others) needs any module instance to |
| 1120 | # implement a __nonzero__ method |
| 1121 | main_mod.__nonzero__ = lambda : True |
| 1122 | |
| 1123 | return main_mod |
| 1124 | |
| 1125 | def clear_main_mod_cache(self): |
| 1126 | """Clear the cache of main modules. |
no outgoing calls