py_compile.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. """Routine to "compile" a .py file to a .pyc file.
  2. This module has intimate knowledge of the format of .pyc files.
  3. """
  4. import enum
  5. import importlib._bootstrap_external
  6. import importlib.machinery
  7. import importlib.util
  8. import os
  9. import os.path
  10. import sys
  11. import traceback
  12. __all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"]
  13. class PyCompileError(Exception):
  14. """Exception raised when an error occurs while attempting to
  15. compile the file.
  16. To raise this exception, use
  17. raise PyCompileError(exc_type,exc_value,file[,msg])
  18. where
  19. exc_type: exception type to be used in error message
  20. type name can be accesses as class variable
  21. 'exc_type_name'
  22. exc_value: exception value to be used in error message
  23. can be accesses as class variable 'exc_value'
  24. file: name of file being compiled to be used in error message
  25. can be accesses as class variable 'file'
  26. msg: string message to be written as error message
  27. If no value is given, a default exception message will be
  28. given, consistent with 'standard' py_compile output.
  29. message (or default) can be accesses as class variable
  30. 'msg'
  31. """
  32. def __init__(self, exc_type, exc_value, file, msg=''):
  33. exc_type_name = exc_type.__name__
  34. if exc_type is SyntaxError:
  35. tbtext = ''.join(traceback.format_exception_only(
  36. exc_type, exc_value))
  37. errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
  38. else:
  39. errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
  40. Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
  41. self.exc_type_name = exc_type_name
  42. self.exc_value = exc_value
  43. self.file = file
  44. self.msg = msg or errmsg
  45. def __str__(self):
  46. return self.msg
  47. class PycInvalidationMode(enum.Enum):
  48. TIMESTAMP = 1
  49. CHECKED_HASH = 2
  50. UNCHECKED_HASH = 3
  51. def _get_default_invalidation_mode():
  52. if os.environ.get('SOURCE_DATE_EPOCH'):
  53. return PycInvalidationMode.CHECKED_HASH
  54. else:
  55. return PycInvalidationMode.TIMESTAMP
  56. def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1,
  57. invalidation_mode=None, quiet=0):
  58. """Byte-compile one Python source file to Python bytecode.
  59. :param file: The source file name.
  60. :param cfile: The target byte compiled file name. When not given, this
  61. defaults to the PEP 3147/PEP 488 location.
  62. :param dfile: Purported file name, i.e. the file name that shows up in
  63. error messages. Defaults to the source file name.
  64. :param doraise: Flag indicating whether or not an exception should be
  65. raised when a compile error is found. If an exception occurs and this
  66. flag is set to False, a string indicating the nature of the exception
  67. will be printed, and the function will return to the caller. If an
  68. exception occurs and this flag is set to True, a PyCompileError
  69. exception will be raised.
  70. :param optimize: The optimization level for the compiler. Valid values
  71. are -1, 0, 1 and 2. A value of -1 means to use the optimization
  72. level of the current interpreter, as given by -O command line options.
  73. :param invalidation_mode:
  74. :param quiet: Return full output with False or 0, errors only with 1,
  75. and no output with 2.
  76. :return: Path to the resulting byte compiled file.
  77. Note that it isn't necessary to byte-compile Python modules for
  78. execution efficiency -- Python itself byte-compiles a module when
  79. it is loaded, and if it can, writes out the bytecode to the
  80. corresponding .pyc file.
  81. However, if a Python installation is shared between users, it is a
  82. good idea to byte-compile all modules upon installation, since
  83. other users may not be able to write in the source directories,
  84. and thus they won't be able to write the .pyc file, and then
  85. they would be byte-compiling every module each time it is loaded.
  86. This can slow down program start-up considerably.
  87. See compileall.py for a script/module that uses this module to
  88. byte-compile all installed files (or all files in selected
  89. directories).
  90. Do note that FileExistsError is raised if cfile ends up pointing at a
  91. non-regular file or symlink. Because the compilation uses a file renaming,
  92. the resulting file would be regular and thus not the same type of file as
  93. it was previously.
  94. """
  95. if invalidation_mode is None:
  96. invalidation_mode = _get_default_invalidation_mode()
  97. if cfile is None:
  98. if optimize >= 0:
  99. optimization = optimize if optimize >= 1 else ''
  100. cfile = importlib.util.cache_from_source(file,
  101. optimization=optimization)
  102. else:
  103. cfile = importlib.util.cache_from_source(file)
  104. if os.path.islink(cfile):
  105. msg = ('{} is a symlink and will be changed into a regular file if '
  106. 'import writes a byte-compiled file to it')
  107. raise FileExistsError(msg.format(cfile))
  108. elif os.path.exists(cfile) and not os.path.isfile(cfile):
  109. msg = ('{} is a non-regular file and will be changed into a regular '
  110. 'one if import writes a byte-compiled file to it')
  111. raise FileExistsError(msg.format(cfile))
  112. loader = importlib.machinery.SourceFileLoader('<py_compile>', file)
  113. source_bytes = loader.get_data(file)
  114. try:
  115. code = loader.source_to_code(source_bytes, dfile or file,
  116. _optimize=optimize)
  117. except Exception as err:
  118. py_exc = PyCompileError(err.__class__, err, dfile or file)
  119. if quiet < 2:
  120. if doraise:
  121. raise py_exc
  122. else:
  123. sys.stderr.write(py_exc.msg + '\n')
  124. return
  125. try:
  126. dirname = os.path.dirname(cfile)
  127. if dirname:
  128. os.makedirs(dirname)
  129. except FileExistsError:
  130. pass
  131. if invalidation_mode == PycInvalidationMode.TIMESTAMP:
  132. source_stats = loader.path_stats(file)
  133. bytecode = importlib._bootstrap_external._code_to_timestamp_pyc(
  134. code, source_stats['mtime'], source_stats['size'])
  135. else:
  136. source_hash = importlib.util.source_hash(source_bytes)
  137. bytecode = importlib._bootstrap_external._code_to_hash_pyc(
  138. code,
  139. source_hash,
  140. (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
  141. )
  142. mode = importlib._bootstrap_external._calc_mode(file)
  143. importlib._bootstrap_external._write_atomic(cfile, bytecode, mode)
  144. return cfile
  145. def main(args=None):
  146. """Compile several source files.
  147. The files named in 'args' (or on the command line, if 'args' is
  148. not specified) are compiled and the resulting bytecode is cached
  149. in the normal manner. This function does not search a directory
  150. structure to locate source files; it only compiles files named
  151. explicitly. If '-' is the only parameter in args, the list of
  152. files is taken from standard input.
  153. """
  154. if args is None:
  155. args = sys.argv[1:]
  156. rv = 0
  157. if args == ['-']:
  158. while True:
  159. filename = sys.stdin.readline()
  160. if not filename:
  161. break
  162. filename = filename.rstrip('\n')
  163. try:
  164. compile(filename, doraise=True)
  165. except PyCompileError as error:
  166. rv = 1
  167. sys.stderr.write("%s\n" % error.msg)
  168. except OSError as error:
  169. rv = 1
  170. sys.stderr.write("%s\n" % error)
  171. else:
  172. for filename in args:
  173. try:
  174. compile(filename, doraise=True)
  175. except PyCompileError as error:
  176. # return value to indicate at least one failure
  177. rv = 1
  178. sys.stderr.write("%s\n" % error.msg)
  179. return rv
  180. if __name__ == "__main__":
  181. sys.exit(main())