Portpicker

1.6.0 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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.

import portpicker
import socket

try:
    # Attempt to pick an unused port
    test_port = portpicker.pick_unused_port()
    if test_port != 0:
        print(f"Picked unused port: {test_port}")
        # Verify the port can be bound to (reduces race condition window)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('127.0.0.1', test_port))
        s.listen(1)
        print(f"Successfully bound to and listening on port {test_port}")
        s.close()
    else:
        print("Failed to pick an unused port.")
except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →