ยปCore Development>Code coverage>Lib/py_compile.py

Python code coverage for Lib/py_compile.py

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