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

Delta Between Two Patch Sets: Lib/compileall.py

Issue 16104: Use multiprocessing in compileall script
Left Patch Set: Created 5 years, 4 months ago
Right Patch Set: Created 5 years 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:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Doc/library/compileall.rst ('k') | Lib/test/test_compileall.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
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
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
42 else: 42 else:
43 dfile = None 43 dfile = None
44 if not os.path.isdir(fullname): 44 if not os.path.isdir(fullname):
45 yield fullname 45 yield fullname
46 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and 46 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
47 os.path.isdir(fullname) and not os.path.islink(fullname)): 47 os.path.isdir(fullname) and not os.path.islink(fullname)):
48 yield from _walk_dir(fullname, ddir=dfile, 48 yield from _walk_dir(fullname, ddir=dfile,
49 maxlevels=maxlevels - 1, quiet=quiet) 49 maxlevels=maxlevels - 1, quiet=quiet)
50 50
51 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,
52 quiet=False, legacy=False, optimize=-1, processes=None): 52 quiet=False, legacy=False, optimize=-1, workers=1):
53 """Byte-compile all modules in the given directory tree. 53 """Byte-compile all modules in the given directory tree.
54 54
55 Arguments (only dir is required): 55 Arguments (only dir is required):
56 56
57 dir: the directory to byte-compile 57 dir: the directory to byte-compile
58 maxlevels: maximum recursion level (default 10) 58 maxlevels: maximum recursion level (default 10)
59 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
60 file as it is compiled into each byte-code file. 60 file as it is compiled into each byte-code file.
61 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
62 quiet: if True, be quiet during compilation 62 quiet: if True, be quiet during compilation
63 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
64 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 65 workers: maximum number of parallel workers
66 """ 66 """
67 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels, 67 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
68 ddir=ddir) 68 ddir=ddir)
69 success = 1 69 success = 1
70 if processes is not None: 70 if workers is not None and workers != 1:
71 if processes < 1: 71 if workers < 0:
72 raise ValueError('processes must be greater than 0') 72 raise ValueError('workers must be greater or equal to 0')
73 if ProcessPoolExecutor is None: 73 if ProcessPoolExecutor is None:
74 raise ValueError('multiprocessing support not available') 74 raise NotImplementedError('multiprocessing support not available')
75 with ProcessPoolExecutor(max_workers=processes) as executor: 75
76 workers = workers or os.cpu_count()
brett.cannon 2014/09/12 16:21:59 This can be `workers or None` as that will default
77 with ProcessPoolExecutor(max_workers=workers) as executor:
76 results = executor.map(partial(compile_file, 78 results = executor.map(partial(compile_file,
77 ddir=ddir, force=force, 79 ddir=ddir, force=force,
78 rx=rx, quiet=quiet, 80 rx=rx, quiet=quiet,
79 legacy=legacy, 81 legacy=legacy,
80 optimize=optimize), 82 optimize=optimize),
81 files) 83 files)
82 success = min(results, default=1) 84 success = min(results, default=1)
83 else: 85 else:
84 for file in files: 86 for file in files:
85 if not compile_file(file, ddir, force, rx, quiet, 87 if not compile_file(file, ddir, force, rx, quiet,
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
188 190
189 def main(): 191 def main():
190 """Script main program.""" 192 """Script main program."""
191 import argparse 193 import argparse
192 194
193 parser = argparse.ArgumentParser( 195 parser = argparse.ArgumentParser(
194 description='Utilities to support installing Python libraries.') 196 description='Utilities to support installing Python libraries.')
195 parser.add_argument('-l', action='store_const', const=0, 197 parser.add_argument('-l', action='store_const', const=0,
196 default=10, dest='maxlevels', 198 default=10, dest='maxlevels',
197 help="don't recurse into subdirectories") 199 help="don't recurse into subdirectories")
200 parser.add_argument('-r', type=int, dest='recursion',
201 help=('control the maximum recursion level. '
202 'if `-l` and `-r` options are specified, '
203 'then `-r` takes precedence.'))
198 parser.add_argument('-f', action='store_true', dest='force', 204 parser.add_argument('-f', action='store_true', dest='force',
199 help='force rebuild even if timestamps are up to date') 205 help='force rebuild even if timestamps are up to date')
200 parser.add_argument('-q', action='store_true', dest='quiet', 206 parser.add_argument('-q', action='store_true', dest='quiet',
201 help='output only error messages') 207 help='output only error messages')
202 parser.add_argument('-b', action='store_true', dest='legacy', 208 parser.add_argument('-b', action='store_true', dest='legacy',
203 help='use legacy (pre-PEP3147) compiled file locations') 209 help='use legacy (pre-PEP3147) compiled file locations')
204 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None, 210 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
205 help=('directory to prepend to file paths for use in ' 211 help=('directory to prepend to file paths for use in '
206 'compile-time tracebacks and in runtime ' 212 'compile-time tracebacks and in runtime '
207 'tracebacks in cases where the source file is ' 213 'tracebacks in cases where the source file is '
208 'unavailable')) 214 'unavailable'))
209 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None, 215 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
210 help=('skip files matching the regular expression; ' 216 help=('skip files matching the regular expression; '
211 'the regexp is searched for in the full path ' 217 'the regexp is searched for in the full path '
212 'of each file considered for compilation')) 218 'of each file considered for compilation'))
213 parser.add_argument('-i', metavar='FILE', dest='flist', 219 parser.add_argument('-i', metavar='FILE', dest='flist',
214 help=('add all the files and directories listed in ' 220 help=('add all the files and directories listed in '
215 'FILE to the list considered for compilation; ' 221 'FILE to the list considered for compilation; '
216 'if "-", names are read from stdin')) 222 'if "-", names are read from stdin'))
217 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*', 223 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
218 help=('zero or more file and directory names ' 224 help=('zero or more file and directory names '
219 'to compile; if no arguments given, defaults ' 225 'to compile; if no arguments given, defaults '
220 'to the equivalent of -l sys.path')) 226 'to the equivalent of -l sys.path'))
221 parser.add_argument('-j', '--processes', default=None, 227 parser.add_argument('-j', '--workers', default=1,
222 type=int, help='Run compileall concurrently') 228 type=int, help='Run compileall concurrently')
223 229
224 args = parser.parse_args() 230 args = parser.parse_args()
225 compile_dests = args.compile_dest 231 compile_dests = args.compile_dest
226 232
227 if (args.ddir and (len(compile_dests) != 1 233 if (args.ddir and (len(compile_dests) != 1
228 or not os.path.isdir(compile_dests[0]))): 234 or not os.path.isdir(compile_dests[0]))):
229 parser.exit('-d destdir requires exactly one directory argument') 235 parser.exit('-d destdir requires exactly one directory argument')
230 if args.rx: 236 if args.rx:
231 import re 237 import re
232 args.rx = re.compile(args.rx) 238 args.rx = re.compile(args.rx)
239
240
241 if args.recursion is not None:
242 maxlevels = args.recursion
243 else:
244 maxlevels = args.maxlevels
233 245
234 # if flist is provided then load it 246 # if flist is provided then load it
235 if args.flist: 247 if args.flist:
236 try: 248 try:
237 with (sys.stdin if args.flist=='-' else open(args.flist)) as f: 249 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
238 for line in f: 250 for line in f:
239 compile_dests.append(line.strip()) 251 compile_dests.append(line.strip())
240 except OSError: 252 except OSError:
241 print("Error reading file list {}".format(args.flist)) 253 print("Error reading file list {}".format(args.flist))
242 return False 254 return False
243 255
244 if args.processes is not None: 256 if args.workers is not None:
245 args.processes = args.processes or os.cpu_count() 257 args.workers = args.workers or os.cpu_count()
brett.cannon 2014/09/12 16:21:59 This can be `args.workers or None`.
246 258
247 success = True 259 success = True
248 try: 260 try:
249 if compile_dests: 261 if compile_dests:
250 for dest in compile_dests: 262 for dest in compile_dests:
251 if os.path.isfile(dest): 263 if os.path.isfile(dest):
252 if not compile_file(dest, args.ddir, args.force, args.rx, 264 if not compile_file(dest, args.ddir, args.force, args.rx,
253 args.quiet, args.legacy): 265 args.quiet, args.legacy):
254 success = False 266 success = False
255 else: 267 else:
256 if not compile_dir(dest, args.maxlevels, args.ddir, 268 if not compile_dir(dest, maxlevels, args.ddir,
257 args.force, args.rx, args.quiet, 269 args.force, args.rx, args.quiet,
258 args.legacy, processes=args.processes): 270 args.legacy, workers=args.workers):
259 success = False 271 success = False
260 return success 272 return success
261 else: 273 else:
262 return compile_path(legacy=args.legacy, force=args.force, 274 return compile_path(legacy=args.legacy, force=args.force,
263 quiet=args.quiet) 275 quiet=args.quiet)
264 except KeyboardInterrupt: 276 except KeyboardInterrupt:
265 print("\n[interrupted]") 277 print("\n[interrupted]")
266 return False 278 return False
267 return True 279 return True
268 280
269 281
270 if __name__ == '__main__': 282 if __name__ == '__main__':
271 exit_status = int(not main()) 283 exit_status = int(not main())
272 sys.exit(exit_status) 284 sys.exit(exit_status)
LEFTRIGHT

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