Return (filename, archivename) for the path. Given a module name path, return the correct file path and archive name, compiling if necessary. For example, given /python/lib/string, return (/python/lib/string.pyc, string).
(self, pathname, basename)
| 2108 | self.write(fname, arcname) |
| 2109 | |
| 2110 | def _get_codename(self, pathname, basename): |
| 2111 | """Return (filename, archivename) for the path. |
| 2112 | |
| 2113 | Given a module name path, return the correct file path and |
| 2114 | archive name, compiling if necessary. For example, given |
| 2115 | /python/lib/string, return (/python/lib/string.pyc, string). |
| 2116 | """ |
| 2117 | def _compile(file, optimize=-1): |
| 2118 | import py_compile |
| 2119 | if self.debug: |
| 2120 | print("Compiling", file) |
| 2121 | try: |
| 2122 | py_compile.compile(file, doraise=True, optimize=optimize) |
| 2123 | except py_compile.PyCompileError as err: |
| 2124 | print(err.msg) |
| 2125 | return False |
| 2126 | return True |
| 2127 | |
| 2128 | file_py = pathname + ".py" |
| 2129 | file_pyc = pathname + ".pyc" |
| 2130 | pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') |
| 2131 | pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) |
| 2132 | pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) |
| 2133 | if self._optimize == -1: |
| 2134 | # legacy mode: use whatever file is present |
| 2135 | if (os.path.isfile(file_pyc) and |
| 2136 | os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): |
| 2137 | # Use .pyc file. |
| 2138 | arcname = fname = file_pyc |
| 2139 | elif (os.path.isfile(pycache_opt0) and |
| 2140 | os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): |
| 2141 | # Use the __pycache__/*.pyc file, but write it to the legacy pyc |
| 2142 | # file name in the archive. |
| 2143 | fname = pycache_opt0 |
| 2144 | arcname = file_pyc |
| 2145 | elif (os.path.isfile(pycache_opt1) and |
| 2146 | os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): |
| 2147 | # Use the __pycache__/*.pyc file, but write it to the legacy pyc |
| 2148 | # file name in the archive. |
| 2149 | fname = pycache_opt1 |
| 2150 | arcname = file_pyc |
| 2151 | elif (os.path.isfile(pycache_opt2) and |
| 2152 | os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): |
| 2153 | # Use the __pycache__/*.pyc file, but write it to the legacy pyc |
| 2154 | # file name in the archive. |
| 2155 | fname = pycache_opt2 |
| 2156 | arcname = file_pyc |
| 2157 | else: |
| 2158 | # Compile py into PEP 3147 pyc file. |
| 2159 | if _compile(file_py): |
| 2160 | if sys.flags.optimize == 0: |
| 2161 | fname = pycache_opt0 |
| 2162 | elif sys.flags.optimize == 1: |
| 2163 | fname = pycache_opt1 |
| 2164 | else: |
| 2165 | fname = pycache_opt2 |
| 2166 | arcname = file_pyc |
| 2167 | else: |