Packing an entire Python application as a PEX file

752 views Asked by At

How can I pack an entire application -- consisting of a start script and a package -- as a PEX file? The directory structure is like this:

|- venv
|- start.py
|- packagename
|-- otherfile.py

I can pack the start.py file like this:

cd <project directory>
. venv/bin/activate
pex -r requirements.txt -o build/application.pex -e start:main

But when I try to run the application.pex file, I get:

ImportError: No module named 'start'

Am I doing something wrong, or is pex just broken?

1

There are 1 answers

1
KatieL On

Pex doesn't really seem to do un-moduled scripts -- it has an option which appears to do what you're after but in practice always seemed to drop into an interpreter...

What I ended up doing is wrapping it in a script which takes the naked script (containing main()) and putting that into a module and then adding that module along with the dependencies and supplying the entrypoint with -e as you've done. The setup and init are fairly simple to write out somewhere in /tmp

It's a little more work upfront, but it runs well in practice -- the wrapped script can do sanity checks and so on (depending on how your build environment is set up).

{Remember to set the "zip-safe" flag in the temporary module's setup!!}