PageRenderTime 40ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/py_compile.py

https://bitbucket.org/dac_io/pypy
Python | 170 lines | 170 code | 0 blank | 0 comment | 0 complexity | c6e94b69155001b18529a37c096912ed 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. def wr_long(f, x):
  45. """Internal; write a 32-bit int to a file in little-endian order."""
  46. f.write(chr( x & 0xff))
  47. f.write(chr((x >> 8) & 0xff))
  48. f.write(chr((x >> 16) & 0xff))
  49. f.write(chr((x >> 24) & 0xff))
  50. def compile(file, cfile=None, dfile=None, doraise=False):
  51. """Byte-compile one Python source file to Python bytecode.
  52. Arguments:
  53. file: source filename
  54. cfile: target filename; defaults to source with 'c' or 'o' appended
  55. ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo)
  56. dfile: purported filename; defaults to source (this is the filename
  57. that will show up in error messages)
  58. doraise: flag indicating whether or not an exception should be
  59. raised when a compile error is found. If an exception
  60. occurs and this flag is set to False, a string
  61. indicating the nature of the exception will be printed,
  62. and the function will return to the caller. If an
  63. exception occurs and this flag is set to True, a
  64. PyCompileError exception will be raised.
  65. Note that it isn't necessary to byte-compile Python modules for
  66. execution efficiency -- Python itself byte-compiles a module when
  67. it is loaded, and if it can, writes out the bytecode to the
  68. corresponding .pyc (or .pyo) file.
  69. However, if a Python installation is shared between users, it is a
  70. good idea to byte-compile all modules upon installation, since
  71. other users may not be able to write in the source directories,
  72. and thus they won't be able to write the .pyc/.pyo file, and then
  73. they would be byte-compiling every module each time it is loaded.
  74. This can slow down program start-up considerably.
  75. See compileall.py for a script/module that uses this module to
  76. byte-compile all installed files (or all files in selected
  77. directories).
  78. """
  79. with open(file, 'U') as f:
  80. try:
  81. timestamp = long(os.fstat(f.fileno()).st_mtime)
  82. except AttributeError:
  83. timestamp = long(os.stat(file).st_mtime)
  84. codestring = f.read()
  85. try:
  86. codeobject = __builtin__.compile(codestring, dfile or file,'exec')
  87. except Exception,err:
  88. py_exc = PyCompileError(err.__class__,err.args,dfile or file)
  89. if doraise:
  90. raise py_exc
  91. else:
  92. sys.stderr.write(py_exc.msg + '\n')
  93. return
  94. if cfile is None:
  95. cfile = file + (__debug__ and 'c' or 'o')
  96. with open(cfile, 'wb') as fc:
  97. fc.write('\0\0\0\0')
  98. wr_long(fc, timestamp)
  99. marshal.dump(codeobject, fc)
  100. fc.flush()
  101. fc.seek(0, 0)
  102. fc.write(MAGIC)
  103. def main(args=None):
  104. """Compile several source files.
  105. The files named in 'args' (or on the command line, if 'args' is
  106. not specified) are compiled and the resulting bytecode is cached
  107. in the normal manner. This function does not search a directory
  108. structure to locate source files; it only compiles files named
  109. explicitly. If '-' is the only parameter in args, the list of
  110. files is taken from standard input.
  111. """
  112. if args is None:
  113. args = sys.argv[1:]
  114. rv = 0
  115. if args == ['-']:
  116. while True:
  117. filename = sys.stdin.readline()
  118. if not filename:
  119. break
  120. filename = filename.rstrip('\n')
  121. try:
  122. compile(filename, doraise=True)
  123. except PyCompileError as error:
  124. rv = 1
  125. sys.stderr.write("%s\n" % error.msg)
  126. except IOError as error:
  127. rv = 1
  128. sys.stderr.write("%s\n" % error)
  129. else:
  130. for filename in args:
  131. try:
  132. compile(filename, doraise=True)
  133. except PyCompileError as error:
  134. # return value to indicate at least one failure
  135. rv = 1
  136. sys.stderr.write(error.msg)
  137. return rv
  138. if __name__ == "__main__":
  139. sys.exit(main())