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)
| 2275 | self.write(fname, arcname) |
| 2276 | |
| 2277 | def _get_codename(self, pathname, basename): |
| 2278 | """Return (filename, archivename) for the path. |
| 2279 | |
| 2280 | Given a module name path, return the correct file path and |
| 2281 | archive name, compiling if necessary. For example, given |
| 2282 | /python/lib/string, return (/python/lib/string.pyc, string). |
| 2283 | """ |
| 2284 | def _compile(file, optimize=-1): |
| 2285 | import py_compile |
| 2286 | if self.debug: |
| 2287 | print("Compiling", file) |
| 2288 | try: |
| 2289 | py_compile.compile(file, doraise=True, optimize=optimize) |
| 2290 | except py_compile.PyCompileError as err: |
| 2291 | print(err.msg) |
| 2292 | return False |
| 2293 | return True |
| 2294 | |
| 2295 | file_py = pathname + ".py" |
| 2296 | file_pyc = pathname + ".pyc" |
| 2297 | pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') |
| 2298 | pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) |
| 2299 | pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) |
| 2300 | if self._optimize == -1: |
| 2301 | # legacy mode: use whatever file is present |
| 2302 | if (os.path.isfile(file_pyc) and |
| 2303 | os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): |
| 2304 | # Use .pyc file. |
| 2305 | arcname = fname = file_pyc |
| 2306 | elif (os.path.isfile(pycache_opt0) and |
| 2307 | os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): |
| 2308 | # Use the __pycache__/*.pyc file, but write it to the legacy pyc |
| 2309 | # file name in the archive. |
| 2310 | fname = pycache_opt0 |
| 2311 | arcname = file_pyc |
| 2312 | elif (os.path.isfile(pycache_opt1) and |
| 2313 | os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): |
| 2314 | # Use the __pycache__/*.pyc file, but write it to the legacy pyc |
| 2315 | # file name in the archive. |
| 2316 | fname = pycache_opt1 |
| 2317 | arcname = file_pyc |
| 2318 | elif (os.path.isfile(pycache_opt2) and |
| 2319 | os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): |
| 2320 | # Use the __pycache__/*.pyc file, but write it to the legacy pyc |
| 2321 | # file name in the archive. |
| 2322 | fname = pycache_opt2 |
| 2323 | arcname = file_pyc |
| 2324 | else: |
| 2325 | # Compile py into PEP 3147 pyc file. |
| 2326 | if _compile(file_py): |
| 2327 | if sys.flags.optimize == 0: |
| 2328 | fname = pycache_opt0 |
| 2329 | elif sys.flags.optimize == 1: |
| 2330 | fname = pycache_opt1 |
| 2331 | else: |
| 2332 | fname = pycache_opt2 |
| 2333 | arcname = file_pyc |
| 2334 | else: |