From e0fe362335db3c1f60df1698928f18036182c2aa Mon Sep 17 00:00:00 2001 From: Thom Neale Date: Sat, 29 Dec 2012 16:32:46 -0500 Subject: [PATCH] Added function to compile file to bytecode...needs hy hackage --- hy/utils.py | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 hy/utils.py diff --git a/hy/utils.py b/hy/utils.py new file mode 100644 index 0000000..c362e79 --- /dev/null +++ b/hy/utils.py @@ -0,0 +1,57 @@ +import os +import imp +import marshall + + +MAGIC = imp.get_magic() + +def _write_long(fp, int_): + """Internal; write a 32-bit int to a file in little-endian order.""" + fp.write(chr( int_ & 0xff)) + fp.write(chr((int_ >> 8) & 0xff)) + fp.write(chr((int_ >> 16) & 0xff)) + fp.write(chr((int_ >> 24) & 0xff)) + + +def write_pyc(filename, cfile=None, dfile='source'): + """Byte-compile one Python source file to Python bytecode. + + Arguments: + filename: filename associated with the bytecode (i.e., foo.py) + + cfile: target filename; defaults to source with 'c' or 'o' appended + ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo) + dfile: purported filename; defaults to source (this is the filename + that will show up in error messages) + See http://hg.python.org/cpython/file/2.7/Lib/py_compile.py + """ + # 'U' opens the file in universal line-ending mode. + with open(filename, 'U') as f: + try: + timestamp = long(os.fstat(f.fileno()).st_mtime) + except AttributeError: + timestamp = long(os.stat(filename).st_mtime) + codestring = f.read() + + codeobject = compile(codestring, dfile or self.filename,'exec') + + # Add on the .pyc (or .pyo) filename extension. + if cfile is None: + cfile = filename + (__debug__ and 'c' or 'o') + + # Write out the compiled code. + with open(cfile, 'wb') as f: + + # Write a placeholder for the magic number. + f.write('\0\0\0\0') + + # Write the timestamp. + _write_long(f, timestamp) + + # Dump the bytecode. + marshal.dump(codeobject, f) + + # Write the magic number of the placeholder. + f.flush() + f.seek(0, 0) + f.write(MAGIC)