• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Routine to "compile" a .py file to a .pyc file.
2
3This module has intimate knowledge of the format of .pyc files.
4"""
5
6import importlib._bootstrap_external
7import importlib.machinery
8import importlib.util
9import os
10import os.path
11import sys
12import traceback
13
14__all__ = ["compile", "main", "PyCompileError"]
15
16
17class 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
26
27        exc_type:   exception type to be used in error message
28                    type name can be accesses as class variable
29                    'exc_type_name'
30
31        exc_value:  exception value to be used in error message
32                    can be accesses as class variable 'exc_value'
33
34        file:       name of file being compiled to be used in error message
35                    can be accesses as class variable 'file'
36
37        msg:        string message to be written as error message
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'
42
43    """
44
45    def __init__(self, exc_type, exc_value, file, msg=''):
46        exc_type_name = exc_type.__name__
47        if exc_type is SyntaxError:
48            tbtext = ''.join(traceback.format_exception_only(
49                exc_type, exc_value))
50            errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
51        else:
52            errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
53
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
64
65def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1):
66    """Byte-compile one Python source file to Python bytecode.
67
68    :param file: The source file name.
69    :param cfile: The target byte compiled file name.  When not given, this
70        defaults to the PEP 3147/PEP 488 location.
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.
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
83    :return: Path to the resulting byte compiled file.
84
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
88    corresponding .pyc file.
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,
93    and thus they won't be able to write the .pyc file, and then
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).
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.
105    """
106    if cfile is None:
107        if optimize >= 0:
108            optimization = optimize if optimize >= 1 else ''
109            cfile = importlib.util.cache_from_source(file,
110                                                     optimization=optimization)
111        else:
112            cfile = importlib.util.cache_from_source(file)
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')
116        raise FileExistsError(msg.format(cfile))
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')
120        raise FileExistsError(msg.format(cfile))
121    loader = importlib.machinery.SourceFileLoader('<py_compile>', file)
122    source_bytes = loader.get_data(file)
123    try:
124        code = loader.source_to_code(source_bytes, dfile or file,
125                                     _optimize=optimize)
126    except Exception as err:
127        py_exc = PyCompileError(err.__class__, err, dfile or file)
128        if doraise:
129            raise py_exc
130        else:
131            sys.stderr.write(py_exc.msg + '\n')
132            return
133    try:
134        dirname = os.path.dirname(cfile)
135        if dirname:
136            os.makedirs(dirname)
137    except FileExistsError:
138        pass
139    source_stats = loader.path_stats(file)
140    bytecode = importlib._bootstrap_external._code_to_bytecode(
141            code, source_stats['mtime'], source_stats['size'])
142    mode = importlib._bootstrap_external._calc_mode(file)
143    importlib._bootstrap_external._write_atomic(cfile, bytecode, mode)
144    return cfile
145
146
147def 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
154    explicitly.  If '-' is the only parameter in args, the list of
155    files is taken from standard input.
156
157    """
158    if args is None:
159        args = sys.argv[1:]
160    rv = 0
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)
172            except OSError as error:
173                rv = 1
174                sys.stderr.write("%s\n" % error)
175    else:
176        for filename in args:
177            try:
178                compile(filename, doraise=True)
179            except PyCompileError as error:
180                # return value to indicate at least one failure
181                rv = 1
182                sys.stderr.write("%s\n" % error.msg)
183    return rv
184
185if __name__ == "__main__":
186    sys.exit(main())
187