Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(32593)

Side by Side Diff: Lib/compileall.py

Issue 16104: Use multiprocessing in compileall script
Patch Set: Created 5 years, 4 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
OLDNEW
1 """Module/script to byte-compile all .py files to .pyc (or .pyo) files. 1 """Module/script to byte-compile all .py files to .pyc (or .pyo) files.
2 2
3 When called as a script with arguments, this compiles the directories 3 When called as a script with arguments, this compiles the directories
4 given as arguments recursively; the -l option prevents it from 4 given as arguments recursively; the -l option prevents it from
5 recursing into directories. 5 recursing into directories.
6 6
7 Without arguments, if compiles all modules on sys.path, without 7 Without arguments, if compiles all modules on sys.path, without
8 recursing into subdirectories. (Even though it should do so for 8 recursing into subdirectories. (Even though it should do so for
9 packages -- for now, you'll have to deal with packages separately.) 9 packages -- for now, you'll have to deal with packages separately.)
10 10
11 See module py_compile for details of the actual byte-compilation. 11 See module py_compile for details of the actual byte-compilation.
12 """ 12 """
13 import os 13 import os
14 import sys 14 import sys
15 import importlib.util 15 import importlib.util
16 import py_compile 16 import py_compile
17 import struct 17 import struct
18 18
19 try:
20 from concurrent.futures import ProcessPoolExecutor
21 except ImportError:
22 ProcessPoolExecutor = None
23 from functools import partial
24
19 __all__ = ["compile_dir","compile_file","compile_path"] 25 __all__ = ["compile_dir","compile_file","compile_path"]
20 26
27 def _walk_dir(dir, ddir=None, maxlevels=10, quiet=False):
28 if not quiet:
29 print('Listing {!r}...'.format(dir))
30 try:
31 names = os.listdir(dir)
32 except OSError:
33 print("Can't list {!r}".format(dir))
berkerpeksag 2014/04/27 15:57:05 Should also this needs to wrap with a ``if not qui
Claudiu.Popa 2014/04/27 16:05:13 The original line wasn't wrapped.
34 names = []
35 names.sort()
36 for name in names:
37 if name == '__pycache__':
38 continue
39 fullname = os.path.join(dir, name)
40 if ddir is not None:
41 dfile = os.path.join(ddir, name)
42 else:
43 dfile = None
44 if not os.path.isdir(fullname):
45 yield fullname
46 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
47 os.path.isdir(fullname) and not os.path.islink(fullname)):
48 yield from _walk_dir(fullname, ddir=dfile,
49 maxlevels=maxlevels - 1, quiet=quiet)
50
21 def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None, 51 def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
22 quiet=False, legacy=False, optimize=-1): 52 quiet=False, legacy=False, optimize=-1, processes=None):
23 """Byte-compile all modules in the given directory tree. 53 """Byte-compile all modules in the given directory tree.
24 54
25 Arguments (only dir is required): 55 Arguments (only dir is required):
26 56
27 dir: the directory to byte-compile 57 dir: the directory to byte-compile
28 maxlevels: maximum recursion level (default 10) 58 maxlevels: maximum recursion level (default 10)
29 ddir: the directory that will be prepended to the path to the 59 ddir: the directory that will be prepended to the path to the
30 file as it is compiled into each byte-code file. 60 file as it is compiled into each byte-code file.
31 force: if True, force compilation, even if timestamps are up-to-date 61 force: if True, force compilation, even if timestamps are up-to-date
32 quiet: if True, be quiet during compilation 62 quiet: if True, be quiet during compilation
33 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths 63 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
34 optimize: optimization level or -1 for level of the interpreter 64 optimize: optimization level or -1 for level of the interpreter
65 processes: maximum number of parallel processes
35 """ 66 """
36 if not quiet: 67 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
37 print('Listing {!r}...'.format(dir)) 68 ddir=ddir)
38 try:
39 names = os.listdir(dir)
40 except OSError:
41 print("Can't list {!r}".format(dir))
42 names = []
43 names.sort()
44 success = 1 69 success = 1
45 for name in names: 70 if processes is not None:
46 if name == '__pycache__': 71 if processes < 1:
47 continue 72 raise ValueError('processes must be greater than 0')
48 fullname = os.path.join(dir, name) 73 if ProcessPoolExecutor is None:
49 if ddir is not None: 74 raise ValueError('multiprocessing support not available')
50 dfile = os.path.join(ddir, name) 75 with ProcessPoolExecutor(max_workers=processes) as executor:
51 else: 76 results = executor.map(partial(compile_file,
52 dfile = None 77 ddir=ddir, force=force,
53 if not os.path.isdir(fullname): 78 rx=rx, quiet=quiet,
54 if not compile_file(fullname, ddir, force, rx, quiet, 79 legacy=legacy,
80 optimize=optimize),
81 files)
82 success = min(results, default=1)
83 else:
84 for file in files:
85 if not compile_file(file, ddir, force, rx, quiet,
55 legacy, optimize): 86 legacy, optimize):
56 success = 0
57 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
58 os.path.isdir(fullname) and not os.path.islink(fullname)):
59 if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
60 quiet, legacy, optimize):
61 success = 0 87 success = 0
62 return success 88 return success
63 89
64 def compile_file(fullname, ddir=None, force=False, rx=None, quiet=False, 90 def compile_file(fullname, ddir=None, force=False, rx=None, quiet=False,
65 legacy=False, optimize=-1): 91 legacy=False, optimize=-1):
66 """Byte-compile one file. 92 """Byte-compile one file.
67 93
68 Arguments (only fullname is required): 94 Arguments (only fullname is required):
69 95
70 fullname: the file to byte-compile 96 fullname: the file to byte-compile
(...skipping 114 matching lines...) Expand 10 before | Expand all | Expand 10 after
185 'the regexp is searched for in the full path ' 211 'the regexp is searched for in the full path '
186 'of each file considered for compilation')) 212 'of each file considered for compilation'))
187 parser.add_argument('-i', metavar='FILE', dest='flist', 213 parser.add_argument('-i', metavar='FILE', dest='flist',
188 help=('add all the files and directories listed in ' 214 help=('add all the files and directories listed in '
189 'FILE to the list considered for compilation; ' 215 'FILE to the list considered for compilation; '
190 'if "-", names are read from stdin')) 216 'if "-", names are read from stdin'))
191 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*', 217 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
192 help=('zero or more file and directory names ' 218 help=('zero or more file and directory names '
193 'to compile; if no arguments given, defaults ' 219 'to compile; if no arguments given, defaults '
194 'to the equivalent of -l sys.path')) 220 'to the equivalent of -l sys.path'))
221 parser.add_argument('-j', '--processes', action='store', default=None,
berkerpeksag 2014/04/27 15:57:05 You could remove ``action='store'``. It is already
222 type=int, help='Run compileall concurrently')
223
195 args = parser.parse_args() 224 args = parser.parse_args()
196
197 compile_dests = args.compile_dest 225 compile_dests = args.compile_dest
198 226
199 if (args.ddir and (len(compile_dests) != 1 227 if (args.ddir and (len(compile_dests) != 1
200 or not os.path.isdir(compile_dests[0]))): 228 or not os.path.isdir(compile_dests[0]))):
201 parser.exit('-d destdir requires exactly one directory argument') 229 parser.exit('-d destdir requires exactly one directory argument')
202 if args.rx: 230 if args.rx:
203 import re 231 import re
204 args.rx = re.compile(args.rx) 232 args.rx = re.compile(args.rx)
205 233
206 # if flist is provided then load it 234 # if flist is provided then load it
207 if args.flist: 235 if args.flist:
208 try: 236 try:
209 with (sys.stdin if args.flist=='-' else open(args.flist)) as f: 237 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
210 for line in f: 238 for line in f:
211 compile_dests.append(line.strip()) 239 compile_dests.append(line.strip())
212 except OSError: 240 except OSError:
213 print("Error reading file list {}".format(args.flist)) 241 print("Error reading file list {}".format(args.flist))
214 return False 242 return False
243
244 if args.processes is not None:
245 if args.processes == 0:
246 args.processes = os.cpu_count()
berkerpeksag 2014/04/27 15:57:05 Nitpick: args.processes = args.processes or os.cpu
215 247
216 success = True 248 success = True
217 try: 249 try:
218 if compile_dests: 250 if compile_dests:
219 for dest in compile_dests: 251 for dest in compile_dests:
220 if os.path.isfile(dest): 252 if os.path.isfile(dest):
221 if not compile_file(dest, args.ddir, args.force, args.rx, 253 if not compile_file(dest, args.ddir, args.force, args.rx,
222 args.quiet, args.legacy): 254 args.quiet, args.legacy):
223 success = False 255 success = False
224 else: 256 else:
225 if not compile_dir(dest, args.maxlevels, args.ddir, 257 if not compile_dir(dest, args.maxlevels, args.ddir,
226 args.force, args.rx, args.quiet, 258 args.force, args.rx, args.quiet,
227 args.legacy): 259 args.legacy, processes=args.processes):
228 success = False 260 success = False
229 return success 261 return success
230 else: 262 else:
231 return compile_path(legacy=args.legacy, force=args.force, 263 return compile_path(legacy=args.legacy, force=args.force,
232 quiet=args.quiet) 264 quiet=args.quiet)
233 except KeyboardInterrupt: 265 except KeyboardInterrupt:
234 print("\n[interrupted]") 266 print("\n[interrupted]")
235 return False 267 return False
236 return True 268 return True
237 269
238 270
239 if __name__ == '__main__': 271 if __name__ == '__main__':
240 exit_status = int(not main()) 272 exit_status = int(not main())
241 sys.exit(exit_status) 273 sys.exit(exit_status)
OLDNEW

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+