Skip to content

Instantly share code, notes, and snippets.

@simeonf
Last active January 9, 2024 05:11
Show Gist options
  • Save simeonf/062af826e79259bc7686 to your computer and use it in GitHub Desktop.
Save simeonf/062af826e79259bc7686 to your computer and use it in GitHub Desktop.
Creating a PEX from a python script

So you want to create a pex that packages your script and its dependencies?

Ok - first to make our script! Call it foo.py:

import requests

if __name__ == '__main__':
  req = requests.get("https://raw.githubusercontent.com/pantsbuild/pex/master/README.rst")
  print req.text.split("\n")[0]

It's a requests hello world program. To package it we need a minimal setup.py for distributing a script. Put it in the same directory:

from distutils.core import setup
setup(name='foo',
    version='1.0',
    scripts=['foo.py'],
    )

Now that our script is packageable we can use pex to build an executable out of it:

$ pex . requests -c foo.py -o foo.pex -f dist

Briefly - requests and . are our dependencies. -c foo.py tells pex what to run. And -o foo.pex creates the output file.

You should get a foo.pex file in the same directory. Run it to see the script execute:

$ ./foo.pex
PEX

And you can unzip the pex to see the contents including the packaged dependencies:

$ unzip -t foo.pex
... much output not shown...
@Caleb9
Copy link

Caleb9 commented Jan 16, 2022

Thanks so much for the article, I got it working finally :). One extra thing I needed to do to make this work was to add a python shebang #!/usr/bin/env python3 on top of main.py file. Supposedly there's been a change in pex 2.1.46 making this necessary. Note that this particular shebang works on Debian and its derivatives, but might be different for other distros (not sure though).

@shearn89
Copy link

@Caleb9 ah cool, glad it helped! I'll update the article with a link to that post, cheers for the heads up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment