pex - Python Executable

Tue Jan 7, 2020

What is pex

pex is a smart utility to create the single file independent Python environment, with which you can run Python based programs just like it is a executable program.

Creating pex

to create an environment with pex:

$ pex requests -o myenv.pex
  • the list of dependencies here is just requests package
  • can add more than one dependencies like below:

    # etc below is just the placeholder!
    $ pex requests flask etc -o myenv.pex
  • to pin the package to a particular version use:

    $ pex 'flask==1.1.1' -o myenv.pex
    # or
    $ pex 'flask<1.1.1' -o myenv.pex
  • can create the env with the dependencies as prescribed in requirements file as below:

    $ pex -r requirements.txt -o myenv.pex

Running a pex

to run the program with pex:

$ ./myenv.pex 
  • this way your program will work as if you have activated the environment, and running your program with python as below:

    # after activating the env
    $ python

Now this would suffice for most of scenarios, but for few, we would need to use/run with some different executable (not python as in this case).

For example, running flask applications using flask command, or running with gunicorn, uvicorn etc.

In such cases, need to change the PEX_SCRIPT as done in below example for running the web app with gunicorn.

$ PEX_SCRIPT=gunicorn ./httpx.pex -w 2 fastapi_demo:app -k uvicorn.workers.UvicornWorker


Since pex essentially makes an one file - “zipped” python environment, there are many more useful ways and scenarios in which this tool would be very helpful.

Will add more ways of using this tool as I explore it more.

comments powered by Disqus