Can I zip all the python standard libs and the python still able to import it?

前端 未结 1 431
你的背包
你的背包 2021-01-22 08:16

I read a tutorial that you can compile all the libs files to .pyc, then pack all the .pyc as a zipped file. Then the python still works as magic and it becomes significantly sma

1条回答
  •  时光说笑
    2021-01-22 08:48

    To import modules from a .zip file, you need to add that file to sys.path - then it will act as a search directory. The zipimport module that does the job is a built-in one.


    sys.path is constructed like this:

    • PYTHONPATH environment variable + value calculated from a compiled-in default (PYTHONPATH macro in pyconfig.h)
      • The calculated value includes a path to a .zip file that may or may not exist.
    • Then site is imported that does the following:
      • looks for and adds user-specific site-packages
      • looks for system-wide site-packages directories under sys.prefix and sys.exec_prefix.
        • when calculating both sys properties, the interpreter does a number of tests that includes looking for os.py file and lib-dynload directory where they should normally be
      • scans the site-packages directories for .pth files and appends their lines to sys.path, treating them as paths relative to the file's location.

    So, you can move all the standard modules into the predefined .zip file. But you may need to leave an os.py or lib-dynload if sys.prefix and sys.exec_prefix become blank after that (the contents are irrelevant, the moved modules will be imported from the .zip because it's earlier on sys.path), or you will lose access to all 3rd-party modules.

    Subdirectories that have their own entry in sys.path you need to handle separately so that their contents can still be found on sys.path.

    (tested in Python 2.7-win32)


    Though adding .pyc files to the archive is sufficient, pdb and stacktraces will be useless unless you place .pys there as well.

    0 讨论(0)
提交回复
热议问题