July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: David Goodger
You need to
move (or share, via a network-shared filesystem)
.py modules between different platforms without
worrying about the different ways the platforms represent
end-of-line.
Python’s import hooks are mostly used for advanced,
complicated tasks, but can sometimes come in handy for a simple
system-administration task, such as dealing with this
recipe’s problem. Put this code in your
sitecustomize.py, which can be located anywhere on
sys.path, and you’ll be able to
import Python modules with any Unix, Mac, or Windows line endings:
import ihooks, imp, py_compile
class MyHooks(ihooks.Hooks):
def load_source(self, name, filename, file=None):
""" Compile source files with any line ending. """
if file:
file.close( )
py_compile.compile(filename) # Line-ending conversion is in here cfile = open(filename + (_ _debug_ _ and 'c' or 'o'), 'rb') try: return self.load_compiled(name, filename, cfile) finally: cfile.close( ) class MyModuleLoader(ihooks.ModuleLoader): def load_module(self, name, stuff): """ Special-case package directory imports """ file, filename, (suff, mode, type) = stuff path = None if type == imp.PKG_DIRECTORY: stuff = self.find_module_in_dir("_ _init_ _", filename, 0) file = stuff[0] # package/_ _init_ _.py path = [filename] try: # Let superclass handle the rest module = ihooks.ModuleLoader.load_module(self, name, stuff) finally: if file: file.close( ) if path: module._ _path_ ...Read now
Unlock full access