portpicker
Pure-Python module for finding unused network ports on a host
Repository Health
Technical Analysis
portpicker is a small, dependency-free Python module from Google for finding unused network ports. Its core is a single pick_unused_port() function that returns a free TCP/UDP port number, which is invaluable when spinning up test servers, fixtures, or subprocesses that each need their own port.
Beyond the simple function, portpicker ships an optional port server: a daemon that coordinates port allocation across every process on a host so that heavily loaded test clusters can obtain guaranteed-unique ports without race conditions. It can be used as an imported library or called from the command line in shell scripts.
What You Get
- A pure-Python pick_unused_port() function with no third-party dependencies
- An optional port server daemon that coordinates unique port allocation across all host processes
- Command-line usage for grabbing a free port inside shell scripts
- Support for reserving ports tied to a process PID via the PORTSERVER_ADDRESS environment variable
- A permissive Apache-2.0 license from Google
Common Use Cases
- Assigning a free port to a test server or fixture before it starts listening
- Coordinating unique ports across many parallel tests on a loaded CI host via the port server
- Grabbing an available port inside a shell script for ad-hoc tooling
Under The Hood
Architecture - The module is two files under src/: portpicker.py implements pick_unused_port() by asking the OS for an ephemeral port (binding a socket to port 0) and, when a PORTSERVER_ADDRESS is set, delegating to a coordinating daemon over a unix socket. portserver.py implements that daemon, which reads a PID from each connection, tests candidate ports, and hands back a unique assignment reclaimed only when the owning process exits.
Tech Stack - Pure Python with no third-party runtime dependencies, packaged via pyproject.toml and setup.cfg. It uses only the standard library socket module for port probing and works from Python 3 onward (with legacy 1.3.x releases for Python 2).
Code Quality - The repository includes a tests directory and a test.sh runner, a ChangeLog, and a CONTRIBUTING guide. The code is deliberately small and readable, reflecting its status as a long-lived, stable Google utility, though recent development activity is low.
API Design - The public API is about as minimal as it gets: import portpicker; portpicker.pick_unused_port(). Coordination with the port server is transparent and driven entirely by an environment variable, so callers do not change their code to benefit from it. The README is candid about race-condition caveats, which sets accurate expectations for correct use.