|
| 1 | + |
| 2 | +from pathlib import Path |
| 3 | +import os |
| 4 | +import py_compile |
| 5 | + |
| 6 | + |
| 7 | +def compile_file(source_file: Path, delete=False) -> bool: |
| 8 | + target_file = str(source_file) + 'c' |
| 9 | + try: |
| 10 | + ok = py_compile.compile(source_file, target_file) |
| 11 | + if delete: |
| 12 | + source_file.unlink() |
| 13 | + except py_compile.PyCompileError as err: |
| 14 | + print(f'*** Error compiling {source_file}...') |
| 15 | + # escape non-printable characters in msg |
| 16 | + encoding = sys.stdout.encoding or sys.getdefaultencoding() |
| 17 | + msg = err.msg.encode(encoding, errors='backslashreplace').decode(encoding) |
| 18 | + print(msg) |
| 19 | + return False |
| 20 | + except (SyntaxError, UnicodeError, OSError) as e: |
| 21 | + print(f'*** Error compiling {source_file}...') |
| 22 | + print(e.__class__.__name__ + ':', e) |
| 23 | + return False |
| 24 | + else: |
| 25 | + return ok != 0 |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +def main(): |
| 30 | + import argparse |
| 31 | + """Script main program.""" |
| 32 | + |
| 33 | + parser = argparse.ArgumentParser(description='Utilities to compile *.py to *.pyc.') |
| 34 | + parser.add_argument('-d', '--delete', action='store_true', dest='delete', default=False, help='delete source files') |
| 35 | + parser.add_argument('compile_dests', metavar='FILE|DIR', nargs='*', help='file or directory names to compile') |
| 36 | + |
| 37 | + args = parser.parse_args() |
| 38 | + |
| 39 | + source_files = [] |
| 40 | + |
| 41 | + for dest in args.compile_dests: |
| 42 | + dest = Path(dest) |
| 43 | + if dest.is_file(): |
| 44 | + source_files.append(dest) |
| 45 | + if dest.is_dir(): |
| 46 | + source_files += list(dest.glob('**/*.py')) |
| 47 | + |
| 48 | + for file in source_files: |
| 49 | + compile_file(file, delete=args.delete) |
| 50 | + |
| 51 | + return True |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + import sys |
| 56 | + exit_status = int(not main()) |
| 57 | + sys.exit(exit_status) |
0 commit comments