Guido van Rossum | 63566e2 | 1998-01-19 04:01:26 +0000 | [diff] [blame] | 1 | """Routine to "compile" a .py file to a .pyc (or .pyo) file. |
| 2 | |
| 3 | This module has intimate knowledge of the format of .pyc files. |
| 4 | """ |
Guido van Rossum | 3bb5448 | 1994-08-29 10:52:58 +0000 | [diff] [blame] | 5 | |
Sjoerd Mullender | 2e5168c | 1995-07-19 11:21:47 +0000 | [diff] [blame] | 6 | import imp |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 7 | import importlib._bootstrap |
| 8 | import importlib.machinery |
Fred Drake | a96f1a3 | 2002-08-21 20:23:22 +0000 | [diff] [blame] | 9 | import os |
| 10 | import sys |
| 11 | import traceback |
| 12 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 13 | __all__ = ["compile", "main", "PyCompileError"] |
| 14 | |
| 15 | |
| 16 | class PyCompileError(Exception): |
| 17 | """Exception raised when an error occurs while attempting to |
| 18 | compile the file. |
| 19 | |
| 20 | To raise this exception, use |
| 21 | |
| 22 | raise PyCompileError(exc_type,exc_value,file[,msg]) |
| 23 | |
| 24 | where |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 25 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 26 | exc_type: exception type to be used in error message |
| 27 | type name can be accesses as class variable |
| 28 | 'exc_type_name' |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 29 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 30 | exc_value: exception value to be used in error message |
| 31 | can be accesses as class variable 'exc_value' |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 32 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 33 | file: name of file being compiled to be used in error message |
| 34 | can be accesses as class variable 'file' |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 35 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 36 | msg: string message to be written as error message |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 37 | If no value is given, a default exception message will be |
| 38 | given, consistent with 'standard' py_compile output. |
| 39 | message (or default) can be accesses as class variable |
| 40 | 'msg' |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 41 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 42 | """ |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 43 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 44 | def __init__(self, exc_type, exc_value, file, msg=''): |
| 45 | exc_type_name = exc_type.__name__ |
| 46 | if exc_type is SyntaxError: |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 47 | tbtext = ''.join(traceback.format_exception_only( |
| 48 | exc_type, exc_value)) |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 49 | errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file) |
| 50 | else: |
| 51 | errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value) |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 52 | |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 53 | Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file) |
| 54 | |
| 55 | self.exc_type_name = exc_type_name |
| 56 | self.exc_value = exc_value |
| 57 | self.file = file |
| 58 | self.msg = msg or errmsg |
| 59 | |
| 60 | def __str__(self): |
| 61 | return self.msg |
| 62 | |
Skip Montanaro | c62c81e | 2001-02-12 02:00:42 +0000 | [diff] [blame] | 63 | |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 64 | def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1): |
Guido van Rossum | 63566e2 | 1998-01-19 04:01:26 +0000 | [diff] [blame] | 65 | """Byte-compile one Python source file to Python bytecode. |
| 66 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 67 | :param file: The source file name. |
| 68 | :param cfile: The target byte compiled file name. When not given, this |
| 69 | defaults to the PEP 3147 location. |
| 70 | :param dfile: Purported file name, i.e. the file name that shows up in |
| 71 | error messages. Defaults to the source file name. |
| 72 | :param doraise: Flag indicating whether or not an exception should be |
| 73 | raised when a compile error is found. If an exception occurs and this |
| 74 | flag is set to False, a string indicating the nature of the exception |
| 75 | will be printed, and the function will return to the caller. If an |
| 76 | exception occurs and this flag is set to True, a PyCompileError |
| 77 | exception will be raised. |
Georg Brandl | 8334fd9 | 2010-12-04 10:26:46 +0000 | [diff] [blame] | 78 | :param optimize: The optimization level for the compiler. Valid values |
| 79 | are -1, 0, 1 and 2. A value of -1 means to use the optimization |
| 80 | level of the current interpreter, as given by -O command line options. |
| 81 | |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 82 | :return: Path to the resulting byte compiled file. |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 83 | |
Guido van Rossum | 63566e2 | 1998-01-19 04:01:26 +0000 | [diff] [blame] | 84 | Note that it isn't necessary to byte-compile Python modules for |
| 85 | execution efficiency -- Python itself byte-compiles a module when |
| 86 | it is loaded, and if it can, writes out the bytecode to the |
| 87 | corresponding .pyc (or .pyo) file. |
| 88 | |
| 89 | However, if a Python installation is shared between users, it is a |
| 90 | good idea to byte-compile all modules upon installation, since |
| 91 | other users may not be able to write in the source directories, |
| 92 | and thus they won't be able to write the .pyc/.pyo file, and then |
| 93 | they would be byte-compiling every module each time it is loaded. |
| 94 | This can slow down program start-up considerably. |
| 95 | |
| 96 | See compileall.py for a script/module that uses this module to |
| 97 | byte-compile all installed files (or all files in selected |
| 98 | directories). |
Guido van Rossum | 63566e2 | 1998-01-19 04:01:26 +0000 | [diff] [blame] | 99 | """ |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 100 | if cfile is None: |
| 101 | if optimize >= 0: |
| 102 | cfile = imp.cache_from_source(file, debug_override=not optimize) |
| 103 | else: |
| 104 | cfile = imp.cache_from_source(file) |
| 105 | loader = importlib.machinery.SourceFileLoader('<py_compile>', file) |
| 106 | source_bytes = loader.get_data(file) |
Guido van Rossum | f984a65 | 1998-09-29 15:57:42 +0000 | [diff] [blame] | 107 | try: |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 108 | code = loader.source_to_code(source_bytes, dfile or file, |
| 109 | _optimize=optimize) |
Guido van Rossum | b940e11 | 2007-01-10 16:19:56 +0000 | [diff] [blame] | 110 | except Exception as err: |
Guido van Rossum | bd4a63e | 2007-08-10 17:36:34 +0000 | [diff] [blame] | 111 | py_exc = PyCompileError(err.__class__, err, dfile or file) |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 112 | if doraise: |
| 113 | raise py_exc |
| 114 | else: |
Georg Brandl | e537d6e | 2005-06-10 17:15:18 +0000 | [diff] [blame] | 115 | sys.stderr.write(py_exc.msg + '\n') |
Martin v. Löwis | 0c6774d | 2003-01-15 11:51:06 +0000 | [diff] [blame] | 116 | return |
Benjamin Peterson | 25216ba | 2010-05-08 19:52:21 +0000 | [diff] [blame] | 117 | try: |
Meador Inge | 22b9b37 | 2011-11-28 09:27:32 -0600 | [diff] [blame] | 118 | dirname = os.path.dirname(cfile) |
| 119 | if dirname: |
| 120 | os.makedirs(dirname) |
Brett Cannon | 14581d5 | 2013-01-26 08:48:36 -0500 | [diff] [blame] | 121 | except FileExistsError: |
| 122 | pass |
| 123 | source_stats = loader.path_stats(file) |
| 124 | bytecode = importlib._bootstrap._code_to_bytecode(code, |
| 125 | source_stats['mtime'], len(source_bytes)) |
| 126 | loader._cache_bytecode(file, cfile, bytecode) |
Barry Warsaw | 28a691b | 2010-04-17 00:19:56 +0000 | [diff] [blame] | 127 | return cfile |
Fred Drake | 61cf440 | 2002-08-21 20:56:21 +0000 | [diff] [blame] | 128 | |
| 129 | def main(args=None): |
| 130 | """Compile several source files. |
| 131 | |
| 132 | The files named in 'args' (or on the command line, if 'args' is |
| 133 | not specified) are compiled and the resulting bytecode is cached |
| 134 | in the normal manner. This function does not search a directory |
| 135 | structure to locate source files; it only compiles files named |
Barry Warsaw | d5f9bf5 | 2010-03-31 21:36:22 +0000 | [diff] [blame] | 136 | explicitly. If '-' is the only parameter in args, the list of |
| 137 | files is taken from standard input. |
Fred Drake | 61cf440 | 2002-08-21 20:56:21 +0000 | [diff] [blame] | 138 | |
| 139 | """ |
| 140 | if args is None: |
| 141 | args = sys.argv[1:] |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 142 | rv = 0 |
Barry Warsaw | d5f9bf5 | 2010-03-31 21:36:22 +0000 | [diff] [blame] | 143 | if args == ['-']: |
| 144 | while True: |
| 145 | filename = sys.stdin.readline() |
| 146 | if not filename: |
| 147 | break |
| 148 | filename = filename.rstrip('\n') |
| 149 | try: |
| 150 | compile(filename, doraise=True) |
| 151 | except PyCompileError as error: |
| 152 | rv = 1 |
| 153 | sys.stderr.write("%s\n" % error.msg) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 154 | except OSError as error: |
Barry Warsaw | d5f9bf5 | 2010-03-31 21:36:22 +0000 | [diff] [blame] | 155 | rv = 1 |
| 156 | sys.stderr.write("%s\n" % error) |
| 157 | else: |
| 158 | for filename in args: |
| 159 | try: |
| 160 | compile(filename, doraise=True) |
Matthias Klose | 1c99473 | 2010-04-20 19:48:04 +0000 | [diff] [blame] | 161 | except PyCompileError as error: |
Barry Warsaw | d5f9bf5 | 2010-03-31 21:36:22 +0000 | [diff] [blame] | 162 | # return value to indicate at least one failure |
| 163 | rv = 1 |
| 164 | sys.stderr.write(error.msg) |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 165 | return rv |
Tim Peters | 2c60f7a | 2003-01-29 03:49:43 +0000 | [diff] [blame] | 166 | |
Fred Drake | 61cf440 | 2002-08-21 20:56:21 +0000 | [diff] [blame] | 167 | if __name__ == "__main__": |
Christian Heimes | dd15f6c | 2008-03-16 00:07:10 +0000 | [diff] [blame] | 168 | sys.exit(main()) |