Oct-14-2018, 08:00 PM
The following function uses the output of
ss -lntu
to solve this problemimport subprocess as sp import re import itertools as itt def find_free_port(start=9000): s = sp.check_output(['ss', '-lntu']).decode() maybusy = set(int(x) for x in re.findall('\d+', s)) return next(itt.filterfalse(maybusy.__contains__, itt.count(start))) if __name__ == '__main__': print('free port:', find_free_port())