Compacting a Python Application into a Single Source File
I have a strange situation where I need to upload a Python source file to a testing server for evaluation, but I want to keep my application organized into multiple file开发者_开发知识库s/modules/packages. Unfortunately, the testing server is out of my control, so I can't modify it to allow me to upload a ZIP file containing my code.
Is there any easy way to take a large number of Python source files encompassing an application and automatically reduce them to a single source file (or .pyc file)? For simplicity, only one file would be considered the "entry point" and have a if __name__ == '__main__'
. The final file still needs to be executable by the Python interpreter, so I can't use a Python-to-EXE generator.
If you can't upload a zip file, perhaps you can follow some of the suggestions contained here. The idea is to create and upload a script file which contains a Python shebang line (ignored by the interpreter) prepended to a zip file archive. You can then either let the Python interpreter read the zip file directly or you execute it from a shell. To make this work, you need to be using at least Python 2.6.
zip testapp.zip *
echo '#!/usr/bin/env python' | cat - testapp.zip > testapp.py
chmod 755 testapp.py
To execute either:
python testapp.py
or:
./testapp.py
As discussed in the blog post, depending on what versions are Python you need to support and what features you need, there are various adjustments you may need to make to your source layout to include the necessary __main__.py
files and __init__.py
files to create a proper package and to create a symlinked __main__.py
outside of the main package directory. It's a bit of a kludge but, once you get it working, it should be easy to automate, assuming your testing server can handle such a pseudo text file. The key insight here is that the Python interpreter itself is reading and unzipping the zip archive, not an external program.
If the testing server can handle standard POSIX shell scripts, another option might be to create a script that wraps everything into a set of here files within one big script.
精彩评论