/Lib/py_compile.py

http://unladen-swallow.googlecode.com/ · Python · 168 lines · 151 code · 6 blank · 11 comment · 4 complexity · 4fc271715098bc38abd1d2edd909251b MD5 · raw file

  1. """Routine to "compile" a .py file to a .pyc (or .pyo) file.
  2. This module has intimate knowledge of the format of .pyc files.
  3. """
  4. import __builtin__
  5. import imp
  6. import marshal
  7. import os
  8. import sys
  9. import traceback
  10. MAGIC = imp.get_magic()
  11. __all__ = ["compile", "main", "PyCompileError"]
  12. class PyCompileError(Exception):
  13. """Exception raised when an error occurs while attempting to
  14. compile the file.
  15. To raise this exception, use
  16. raise PyCompileError(exc_type,exc_value,file[,msg])
  17. where
  18. exc_type: exception type to be used in error message
  19. type name can be accesses as class variable
  20. 'exc_type_name'
  21. exc_value: exception value to be used in error message
  22. can be accesses as class variable 'exc_value'
  23. file: name of file being compiled to be used in error message
  24. can be accesses as class variable 'file'
  25. msg: string message to be written as error message
  26. If no value is given, a default exception message will be given,
  27. consistent with 'standard' py_compile output.
  28. message (or default) can be accesses as class variable 'msg'
  29. """
  30. def __init__(self, exc_type, exc_value, file, msg=''):
  31. exc_type_name = exc_type.__name__
  32. if exc_type is SyntaxError:
  33. tbtext = ''.join(traceback.format_exception_only(exc_type, exc_value))
  34. errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
  35. else:
  36. errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
  37. Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
  38. self.exc_type_name = exc_type_name
  39. self.exc_value = exc_value
  40. self.file = file
  41. self.msg = msg or errmsg
  42. def __str__(self):
  43. return self.msg
  44. # Define an internal helper according to the platform
  45. if os.name == "mac":
  46. import MacOS
  47. def set_creator_type(file):
  48. MacOS.SetCreatorAndType(file, 'Pyth', 'PYC ')
  49. else:
  50. def set_creator_type(file):
  51. pass
  52. def wr_long(f, x):
  53. """Internal; write a 32-bit int to a file in little-endian order."""
  54. f.write(chr( x & 0xff))
  55. f.write(chr((x >> 8) & 0xff))
  56. f.write(chr((x >> 16) & 0xff))
  57. f.write(chr((x >> 24) & 0xff))
  58. def compile(file, cfile=None, dfile=None, doraise=False):
  59. """Byte-compile one Python source file to Python bytecode.
  60. Arguments:
  61. file: source filename
  62. cfile: target filename; defaults to source with 'c' or 'o' appended
  63. ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo)
  64. dfile: purported filename; defaults to source (this is the filename
  65. that will show up in error messages)
  66. doraise: flag indicating whether or not an exception should be
  67. raised when a compile error is found. If an exception
  68. occurs and this flag is set to False, a string
  69. indicating the nature of the exception will be printed,
  70. and the function will return to the caller. If an
  71. exception occurs and this flag is set to True, a
  72. PyCompileError exception will be raised.
  73. Note that it isn't necessary to byte-compile Python modules for
  74. execution efficiency -- Python itself byte-compiles a module when
  75. it is loaded, and if it can, writes out the bytecode to the
  76. corresponding .pyc (or .pyo) file.
  77. However, if a Python installation is shared between users, it is a
  78. good idea to byte-compile all modules upon installation, since
  79. other users may not be able to write in the source directories,
  80. and thus they won't be able to write the .pyc/.pyo file, and then
  81. they would be byte-compiling every module each time it is loaded.
  82. This can slow down program start-up considerably.
  83. See compileall.py for a script/module that uses this module to
  84. byte-compile all installed files (or all files in selected
  85. directories).
  86. """
  87. f = open(file, 'U')
  88. try:
  89. timestamp = long(os.fstat(f.fileno()).st_mtime)
  90. except AttributeError:
  91. timestamp = long(os.stat(file).st_mtime)
  92. codestring = f.read()
  93. f.close()
  94. if codestring and codestring[-1] != '\n':
  95. codestring = codestring + '\n'
  96. try:
  97. codeobject = __builtin__.compile(codestring, dfile or file,'exec')
  98. except Exception,err:
  99. py_exc = PyCompileError(err.__class__,err.args,dfile or file)
  100. if doraise:
  101. raise py_exc
  102. else:
  103. sys.stderr.write(py_exc.msg + '\n')
  104. return
  105. if cfile is None:
  106. cfile = file + (__debug__ and 'c' or 'o')
  107. fc = open(cfile, 'wb')
  108. fc.write('\0\0\0\0')
  109. wr_long(fc, timestamp)
  110. marshal.dump(codeobject, fc)
  111. fc.flush()
  112. fc.seek(0, 0)
  113. fc.write(MAGIC)
  114. fc.close()
  115. set_creator_type(cfile)
  116. def main(args=None):
  117. """Compile several source files.
  118. The files named in 'args' (or on the command line, if 'args' is
  119. not specified) are compiled and the resulting bytecode is cached
  120. in the normal manner. This function does not search a directory
  121. structure to locate source files; it only compiles files named
  122. explicitly.
  123. """
  124. if args is None:
  125. args = sys.argv[1:]
  126. rv = 0
  127. for filename in args:
  128. try:
  129. compile(filename, doraise=True)
  130. except PyCompileError, err:
  131. # return value to indicate at least one failure
  132. rv = 1
  133. sys.stderr.write(err.msg)
  134. return rv
  135. if __name__ == "__main__":
  136. sys.exit(main())