Portpicker
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
- gotcha A race condition exists between picking an unused port and your application binding to it. Another process could claim the port in the interim. For critical applications, consider binding to '0' to let the OS assign a port atomically or use a dedicated port server.
- gotcha Repeated calls to `pick_unused_port()` without a port server are not guaranteed to return unique ports, especially on loaded systems. If multiple ports are required, a port server is recommended.
- deprecated Python 2 support is limited to the 1.3.x release series. Later versions, including 1.6.0, are exclusively for Python 3.
Install
-
pip install portpicker
Imports
- pick_unused_port
import portpicker port = portpicker.pick_unused_port()
Quickstart
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}")