Create a runnable binary.

The binary goal creates an executable binary.

In the Python context, this means creating a Pex file from a python_binary target.

The Pex file will contain all the code needed to run the binary, namely:

  • All Python code and resources the binary transitively depends on.
  • The resolved 3rd-party Python dependencies (sdists, eggs and wheels) of all targets the binary transitively depends on.

The Pex metadata will include:

  • The entry point specified by the python_binary target.
  • The intersection of all interpreter constraints applicable to the code in the Pex.


Pex files may be platform-specific

If your code's requirements include source distributions (sdists) that include native code, then the resulting Pex file will only run on the platform it was built on.

However, if all native code requirements are available as wheels for the target platform then you can cross-build a Pex file on a different source platform by specifying the target platform on the python_binary.

See Platforms and manylinux for more information.


Benefit of Pants: binaries only include your true dependencies

Because Pants understands the dependencies of your code, and the dependencies of those dependencies, the generated .pex file will only include the exact code needed for your binary to work. This results in smaller, more focused binaries.


Tip: run <<pantscmd>> target-types --details=python_binary for advanced options

The python_binary target has several advanced options that can change the behavior of Pex. For example, you can specify the platforms the .pex file should work with; change how the .pex file handles sys.path; and mark the .pex file as not-zip-safe.

Run <<pantscmd>> target-types --details=python_binary for more information.


Tip: inspect the .pex file with unzip

Because a .pex file is simply a ZIP file, you can use the Unix tool unzip to inspect the contents. For example, run unzip -l dist/app.pex to see all file members.


To build the binary declared by the python_binary target helloworld:helloworld:

$ <<pantscmd>> binary helloworld

17:36:42 [INFO] Wrote dist/helloworld.pex

Note that we abbreviated the target address to just helloworld, as described here.

You can also build the same binary by running against the file in the target's sources field:

$ <<pantscmd>> binary helloworld/main.py

17:36:42 [INFO] Wrote dist/helloworld.pex