• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Python portpicker module
2
3[![PyPI version](https://badge.fury.io/py/portpicker.svg)](https://badge.fury.io/py/portpicker)
4[![GH Action Status](https://github.com/google/python_portpicker/actions/workflows/python-package.yml/badge.svg)](https://github.com/google/python_portpicker/actions)
5
6This module is useful for finding unused network ports on a host. If you need
7legacy Python 2 support, use the 1.3.x releases.
8
9This module provides a pure Python `pick_unused_port()` function. It can also be
10called via the command line for use in shell scripts.
11
12If your code can accept a bound TCP socket rather than a port number consider
13using `socket.bind(('localhost', 0))` to bind atomically to an available port
14rather than using this library at all.
15
16There is a race condition between picking a port and your application code
17binding to it. The use of a port server by all of your test code to avoid that
18problem is recommended on loaded test hosts running many tests at a time.
19
20Unless you are using a port server, subsequent calls to `pick_unused_port()` to
21obtain an additional port are not guaranteed to return a unique port.
22
23### What is the optional port server?
24
25A port server is intended to be run as a daemon, for use by all processes
26running on the host. It coordinates uses of network ports by anything using a
27portpicker library. If you are using hosts as part of a test automation cluster,
28each one should run a port server as a daemon. You should set the
29`PORTSERVER_ADDRESS=@unittest-portserver` environment variable on all of your
30test runners so that portpicker makes use of it.
31
32A sample port server is included. This portserver implementation works but has
33not spent time in production. If you use it with good results please report back
34so that this statement can be updated to reflect that. :)
35
36A port server listens on a unix socket, reads a pid from a new connection, tests
37the ports it is managing and replies with a port assignment port for that pid. A
38port is only reclaimed for potential reassignment to another process after the
39process it was originally assigned to has died. Processes that need multiple
40ports can simply issue multiple requests and are guaranteed they will each be
41unique.
42
43## Typical usage:
44
45```python
46import portpicker
47test_port = portpicker.pick_unused_port()
48```
49
50Or from the command line:
51
52```bash
53TEST_PORT=`/path/to/portpicker.py $$`
54```
55
56Or, if portpicker is installed as a library on the system Python interpreter:
57
58```bash
59TEST_PORT=`python3 -m portpicker $$`
60```
61
62## DISCLAIMER
63
64This is not an official Google product (experimental or otherwise), it is just
65code that happens to be owned by Google.
66