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