Portpicker is a Python library designed to find unique available network ports. Version 1.6.0, released in August 2023, provides a straightforward API for identifying an open port, primarily intended for use in unittests or by test harnesses launching local servers. It is actively maintained by Google, with releases focusing on stability and Python 3 compatibility.
pip install portpickerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `portpicker.pick_unused_port()` to find an available network port and then attempts to bind a socket to it for immediate verification, mitigating the race condition risk.
After picking a port, immediately attempt to bind to it. For robust multi-process environments, deploy the optional port server and configure clients via the `PORTSERVER_ADDRESS` environment variable to coordinate port allocation.
For multiple unique ports, run the provided port server daemon on your host and set the `PORTSERVER_ADDRESS` environment variable (e.g., `@unittest-portserver`) in your test runners.
Ensure your project targets Python 3.6 or newer. If Python 2 compatibility is essential, pin to `portpicker==1.3.x`.
Install the package using pip: `pip install portpicker`
Ensure `portpicker` is correctly installed and up-to-date (`pip install --upgrade portpicker`). Verify the function call is `portpicker.pick_unused_port()` as shown in the official documentation.
Implement error handling for the `None` return value, e.g., `port = portpicker.pick_unused_port(); if port is None: raise RuntimeError('No unused port found!')`. This issue can also be mitigated by using a port server in highly concurrent test environments.No dependency data recorded yet.