3

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 smaller. But when I zipped all the .pyc files as python36.zip and saved them under /lib/python3.6. Tried to start python, the python says it cannot find module codecs.

What did I do wrong? Can someone explain will this actually work?

J.R.
  • 769
  • 2
  • 10
  • 25

1 Answers1

3

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:


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.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • I checked the sys.path variable and zipped everything as python36 and it works like charm. The only directory I have to leave is the lib-dyload. Cause python calls the dynamic lib from this folder. It seems it is the only thing I cannot zip. – J.R. Oct 27 '17 at 12:04
  • @J.R. you cannot zip `libpythonX.Y.so` because it's the Python engine. [`.so` files that are Python extension modules, you should be able to](https://stackoverflow.com/questions/8601950/load-pyd-files-from-a-zip-from-embedded-python). Just watch that they still can be found on `sys.path` under the same module names. The directory entry itself is tested for in `sys.exec_prefix` search though (updated the answer) so you may need to leave it be. – ivan_pozdeev Oct 27 '17 at 13:26