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