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