PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/compileall.py

https://gitlab.com/unofficial-mirrors/cpython
Python | 295 lines | 273 code | 1 blank | 21 comment | 3 complexity | ede7e4546cc06a958594024d8948dcf2 MD5 | raw file
  1. """Module/script to byte-compile all .py files to .pyc files.
  2. When called as a script with arguments, this compiles the directories
  3. given as arguments recursively; the -l option prevents it from
  4. recursing into directories.
  5. Without arguments, if compiles all modules on sys.path, without
  6. recursing into subdirectories. (Even though it should do so for
  7. packages -- for now, you'll have to deal with packages separately.)
  8. See module py_compile for details of the actual byte-compilation.
  9. """
  10. import os
  11. import sys
  12. import importlib.util
  13. import py_compile
  14. import struct
  15. try:
  16. from concurrent.futures import ProcessPoolExecutor
  17. except ImportError:
  18. ProcessPoolExecutor = None
  19. from functools import partial
  20. __all__ = ["compile_dir","compile_file","compile_path"]
  21. def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0):
  22. if quiet < 2 and isinstance(dir, os.PathLike):
  23. dir = os.fspath(dir)
  24. if not quiet:
  25. print('Listing {!r}...'.format(dir))
  26. try:
  27. names = os.listdir(dir)
  28. except OSError:
  29. if quiet < 2:
  30. print("Can't list {!r}".format(dir))
  31. names = []
  32. names.sort()
  33. for name in names:
  34. if name == '__pycache__':
  35. continue
  36. fullname = os.path.join(dir, name)
  37. if ddir is not None:
  38. dfile = os.path.join(ddir, name)
  39. else:
  40. dfile = None
  41. if not os.path.isdir(fullname):
  42. yield fullname
  43. elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
  44. os.path.isdir(fullname) and not os.path.islink(fullname)):
  45. yield from _walk_dir(fullname, ddir=dfile,
  46. maxlevels=maxlevels - 1, quiet=quiet)
  47. def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
  48. quiet=0, legacy=False, optimize=-1, workers=1):
  49. """Byte-compile all modules in the given directory tree.
  50. Arguments (only dir is required):
  51. dir: the directory to byte-compile
  52. maxlevels: maximum recursion level (default 10)
  53. ddir: the directory that will be prepended to the path to the
  54. file as it is compiled into each byte-code file.
  55. force: if True, force compilation, even if timestamps are up-to-date
  56. quiet: full output with False or 0, errors only with 1,
  57. no output with 2
  58. legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
  59. optimize: optimization level or -1 for level of the interpreter
  60. workers: maximum number of parallel workers
  61. """
  62. if workers is not None and workers < 0:
  63. raise ValueError('workers must be greater or equal to 0')
  64. files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
  65. ddir=ddir)
  66. success = True
  67. if workers is not None and workers != 1 and ProcessPoolExecutor is not None:
  68. workers = workers or None
  69. with ProcessPoolExecutor(max_workers=workers) as executor:
  70. results = executor.map(partial(compile_file,
  71. ddir=ddir, force=force,
  72. rx=rx, quiet=quiet,
  73. legacy=legacy,
  74. optimize=optimize),
  75. files)
  76. success = min(results, default=True)
  77. else:
  78. for file in files:
  79. if not compile_file(file, ddir, force, rx, quiet,
  80. legacy, optimize):
  81. success = False
  82. return success
  83. def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
  84. legacy=False, optimize=-1):
  85. """Byte-compile one file.
  86. Arguments (only fullname is required):
  87. fullname: the file to byte-compile
  88. ddir: if given, the directory name compiled in to the
  89. byte-code file.
  90. force: if True, force compilation, even if timestamps are up-to-date
  91. quiet: full output with False or 0, errors only with 1,
  92. no output with 2
  93. legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
  94. optimize: optimization level or -1 for level of the interpreter
  95. """
  96. success = True
  97. if quiet < 2 and isinstance(fullname, os.PathLike):
  98. fullname = os.fspath(fullname)
  99. name = os.path.basename(fullname)
  100. if ddir is not None:
  101. dfile = os.path.join(ddir, name)
  102. else:
  103. dfile = None
  104. if rx is not None:
  105. mo = rx.search(fullname)
  106. if mo:
  107. return success
  108. if os.path.isfile(fullname):
  109. if legacy:
  110. cfile = fullname + 'c'
  111. else:
  112. if optimize >= 0:
  113. opt = optimize if optimize >= 1 else ''
  114. cfile = importlib.util.cache_from_source(
  115. fullname, optimization=opt)
  116. else:
  117. cfile = importlib.util.cache_from_source(fullname)
  118. cache_dir = os.path.dirname(cfile)
  119. head, tail = name[:-3], name[-3:]
  120. if tail == '.py':
  121. if not force:
  122. try:
  123. mtime = int(os.stat(fullname).st_mtime)
  124. expect = struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
  125. mtime)
  126. with open(cfile, 'rb') as chandle:
  127. actual = chandle.read(8)
  128. if expect == actual:
  129. return success
  130. except OSError:
  131. pass
  132. if not quiet:
  133. print('Compiling {!r}...'.format(fullname))
  134. try:
  135. ok = py_compile.compile(fullname, cfile, dfile, True,
  136. optimize=optimize)
  137. except py_compile.PyCompileError as err:
  138. success = False
  139. if quiet >= 2:
  140. return success
  141. elif quiet:
  142. print('*** Error compiling {!r}...'.format(fullname))
  143. else:
  144. print('*** ', end='')
  145. # escape non-printable characters in msg
  146. msg = err.msg.encode(sys.stdout.encoding,
  147. errors='backslashreplace')
  148. msg = msg.decode(sys.stdout.encoding)
  149. print(msg)
  150. except (SyntaxError, UnicodeError, OSError) as e:
  151. success = False
  152. if quiet >= 2:
  153. return success
  154. elif quiet:
  155. print('*** Error compiling {!r}...'.format(fullname))
  156. else:
  157. print('*** ', end='')
  158. print(e.__class__.__name__ + ':', e)
  159. else:
  160. if ok == 0:
  161. success = False
  162. return success
  163. def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
  164. legacy=False, optimize=-1):
  165. """Byte-compile all module on sys.path.
  166. Arguments (all optional):
  167. skip_curdir: if true, skip current directory (default True)
  168. maxlevels: max recursion level (default 0)
  169. force: as for compile_dir() (default False)
  170. quiet: as for compile_dir() (default 0)
  171. legacy: as for compile_dir() (default False)
  172. optimize: as for compile_dir() (default -1)
  173. """
  174. success = True
  175. for dir in sys.path:
  176. if (not dir or dir == os.curdir) and skip_curdir:
  177. if quiet < 2:
  178. print('Skipping current directory')
  179. else:
  180. success = success and compile_dir(dir, maxlevels, None,
  181. force, quiet=quiet,
  182. legacy=legacy, optimize=optimize)
  183. return success
  184. def main():
  185. """Script main program."""
  186. import argparse
  187. parser = argparse.ArgumentParser(
  188. description='Utilities to support installing Python libraries.')
  189. parser.add_argument('-l', action='store_const', const=0,
  190. default=10, dest='maxlevels',
  191. help="don't recurse into subdirectories")
  192. parser.add_argument('-r', type=int, dest='recursion',
  193. help=('control the maximum recursion level. '
  194. 'if `-l` and `-r` options are specified, '
  195. 'then `-r` takes precedence.'))
  196. parser.add_argument('-f', action='store_true', dest='force',
  197. help='force rebuild even if timestamps are up to date')
  198. parser.add_argument('-q', action='count', dest='quiet', default=0,
  199. help='output only error messages; -qq will suppress '
  200. 'the error messages as well.')
  201. parser.add_argument('-b', action='store_true', dest='legacy',
  202. help='use legacy (pre-PEP3147) compiled file locations')
  203. parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
  204. help=('directory to prepend to file paths for use in '
  205. 'compile-time tracebacks and in runtime '
  206. 'tracebacks in cases where the source file is '
  207. 'unavailable'))
  208. parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
  209. help=('skip files matching the regular expression; '
  210. 'the regexp is searched for in the full path '
  211. 'of each file considered for compilation'))
  212. parser.add_argument('-i', metavar='FILE', dest='flist',
  213. help=('add all the files and directories listed in '
  214. 'FILE to the list considered for compilation; '
  215. 'if "-", names are read from stdin'))
  216. parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
  217. help=('zero or more file and directory names '
  218. 'to compile; if no arguments given, defaults '
  219. 'to the equivalent of -l sys.path'))
  220. parser.add_argument('-j', '--workers', default=1,
  221. type=int, help='Run compileall concurrently')
  222. args = parser.parse_args()
  223. compile_dests = args.compile_dest
  224. if args.rx:
  225. import re
  226. args.rx = re.compile(args.rx)
  227. if args.recursion is not None:
  228. maxlevels = args.recursion
  229. else:
  230. maxlevels = args.maxlevels
  231. # if flist is provided then load it
  232. if args.flist:
  233. try:
  234. with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
  235. for line in f:
  236. compile_dests.append(line.strip())
  237. except OSError:
  238. if args.quiet < 2:
  239. print("Error reading file list {}".format(args.flist))
  240. return False
  241. if args.workers is not None:
  242. args.workers = args.workers or None
  243. success = True
  244. try:
  245. if compile_dests:
  246. for dest in compile_dests:
  247. if os.path.isfile(dest):
  248. if not compile_file(dest, args.ddir, args.force, args.rx,
  249. args.quiet, args.legacy):
  250. success = False
  251. else:
  252. if not compile_dir(dest, maxlevels, args.ddir,
  253. args.force, args.rx, args.quiet,
  254. args.legacy, workers=args.workers):
  255. success = False
  256. return success
  257. else:
  258. return compile_path(legacy=args.legacy, force=args.force,
  259. quiet=args.quiet)
  260. except KeyboardInterrupt:
  261. if args.quiet < 2:
  262. print("\n[interrupted]")
  263. return False
  264. return True
  265. if __name__ == '__main__':
  266. exit_status = int(not main())
  267. sys.exit(exit_status)