blob: 701e8acb9a696354dadff3312a9f62e68c78edf2 [file] [log] [blame]
Guido van Rossum63566e21998-01-19 04:01:26 +00001"""Routine to "compile" a .py file to a .pyc (or .pyo) file.
2
3This module has intimate knowledge of the format of .pyc files.
4"""
Guido van Rossum3bb54481994-08-29 10:52:58 +00005
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +00006import imp
Brett Cannon14581d52013-01-26 08:48:36 -05007import importlib._bootstrap
8import importlib.machinery
Fred Drakea96f1a32002-08-21 20:23:22 +00009import os
10import sys
11import traceback
12
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000013__all__ = ["compile", "main", "PyCompileError"]
14
15
16class 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 Peters2c60f7a2003-01-29 03:49:43 +000025
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000026 exc_type: exception type to be used in error message
27 type name can be accesses as class variable
28 'exc_type_name'
Tim Peters2c60f7a2003-01-29 03:49:43 +000029
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000030 exc_value: exception value to be used in error message
31 can be accesses as class variable 'exc_value'
Tim Peters2c60f7a2003-01-29 03:49:43 +000032
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000033 file: name of file being compiled to be used in error message
34 can be accesses as class variable 'file'
Tim Peters2c60f7a2003-01-29 03:49:43 +000035
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000036 msg: string message to be written as error message
Barry Warsaw28a691b2010-04-17 00:19:56 +000037 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 Peters2c60f7a2003-01-29 03:49:43 +000041
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000042 """
Tim Peters2c60f7a2003-01-29 03:49:43 +000043
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000044 def __init__(self, exc_type, exc_value, file, msg=''):
45 exc_type_name = exc_type.__name__
46 if exc_type is SyntaxError:
Barry Warsaw28a691b2010-04-17 00:19:56 +000047 tbtext = ''.join(traceback.format_exception_only(
48 exc_type, exc_value))
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000049 errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
50 else:
51 errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
Tim Peters2c60f7a2003-01-29 03:49:43 +000052
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000053 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 Montanaroc62c81e2001-02-12 02:00:42 +000063
Georg Brandl8334fd92010-12-04 10:26:46 +000064def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1):
Guido van Rossum63566e21998-01-19 04:01:26 +000065 """Byte-compile one Python source file to Python bytecode.
66
Barry Warsaw28a691b2010-04-17 00:19:56 +000067 :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 Brandl8334fd92010-12-04 10:26:46 +000078 :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 Warsaw28a691b2010-04-17 00:19:56 +000082 :return: Path to the resulting byte compiled file.
Tim Peters2c60f7a2003-01-29 03:49:43 +000083
Guido van Rossum63566e21998-01-19 04:01:26 +000084 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 Rossum63566e21998-01-19 04:01:26 +000099 """
Brett Cannon14581d52013-01-26 08:48:36 -0500100 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 Rossumf984a651998-09-29 15:57:42 +0000107 try:
Brett Cannon14581d52013-01-26 08:48:36 -0500108 code = loader.source_to_code(source_bytes, dfile or file,
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400109 _optimize=optimize)
Guido van Rossumb940e112007-01-10 16:19:56 +0000110 except Exception as err:
Guido van Rossumbd4a63e2007-08-10 17:36:34 +0000111 py_exc = PyCompileError(err.__class__, err, dfile or file)
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000112 if doraise:
113 raise py_exc
114 else:
Georg Brandle537d6e2005-06-10 17:15:18 +0000115 sys.stderr.write(py_exc.msg + '\n')
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000116 return
Benjamin Peterson25216ba2010-05-08 19:52:21 +0000117 try:
Meador Inge22b9b372011-11-28 09:27:32 -0600118 dirname = os.path.dirname(cfile)
119 if dirname:
120 os.makedirs(dirname)
Brett Cannon14581d52013-01-26 08:48:36 -0500121 except FileExistsError:
122 pass
123 source_stats = loader.path_stats(file)
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400124 bytecode = importlib._bootstrap._code_to_bytecode(
125 code, source_stats['mtime'], source_stats['size'])
126 mode = importlib._bootstrap._calc_mode(file)
127 importlib._bootstrap._write_atomic(cfile, bytecode, mode)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000128 return cfile
Fred Drake61cf4402002-08-21 20:56:21 +0000129
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400130
Fred Drake61cf4402002-08-21 20:56:21 +0000131def main(args=None):
132 """Compile several source files.
133
134 The files named in 'args' (or on the command line, if 'args' is
135 not specified) are compiled and the resulting bytecode is cached
136 in the normal manner. This function does not search a directory
137 structure to locate source files; it only compiles files named
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000138 explicitly. If '-' is the only parameter in args, the list of
139 files is taken from standard input.
Fred Drake61cf4402002-08-21 20:56:21 +0000140
141 """
142 if args is None:
143 args = sys.argv[1:]
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000144 rv = 0
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000145 if args == ['-']:
146 while True:
147 filename = sys.stdin.readline()
148 if not filename:
149 break
150 filename = filename.rstrip('\n')
151 try:
152 compile(filename, doraise=True)
153 except PyCompileError as error:
154 rv = 1
155 sys.stderr.write("%s\n" % error.msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200156 except OSError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000157 rv = 1
158 sys.stderr.write("%s\n" % error)
159 else:
160 for filename in args:
161 try:
162 compile(filename, doraise=True)
Matthias Klose1c994732010-04-20 19:48:04 +0000163 except PyCompileError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000164 # return value to indicate at least one failure
165 rv = 1
166 sys.stderr.write(error.msg)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000167 return rv
Tim Peters2c60f7a2003-01-29 03:49:43 +0000168
Fred Drake61cf4402002-08-21 20:56:21 +0000169if __name__ == "__main__":
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000170 sys.exit(main())