Mercurial > repos > shellac > guppy_basecaller
comparison env/lib/python3.7/site-packages/galaxy/util/sockets.py @ 5:9b1c78e6ba9c draft default tip
"planemo upload commit 6c0a8142489327ece472c84e558c47da711a9142"
author | shellac |
---|---|
date | Mon, 01 Jun 2020 08:59:25 -0400 |
parents | 79f47841a781 |
children |
comparison
equal
deleted
inserted
replaced
4:79f47841a781 | 5:9b1c78e6ba9c |
---|---|
1 import random | |
2 import shlex | |
3 import socket | |
4 import subprocess | |
5 | |
6 | |
7 def unused_port(range=None): | |
8 if range: | |
9 return __unused_port_on_range(range) | |
10 else: | |
11 return __unused_port_rangeless() | |
12 | |
13 | |
14 def __unused_port_rangeless(): | |
15 # TODO: Allow ranges (though then need to guess and check)... | |
16 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
17 s.bind(('localhost', 0)) | |
18 addr, port = s.getsockname() | |
19 s.close() | |
20 return port | |
21 | |
22 | |
23 def __unused_port_on_range(range): | |
24 assert range[0] and range[1] | |
25 | |
26 # Find all ports that are already occupied | |
27 cmd_netstat = shlex.split("netstat tuln") | |
28 p1 = subprocess.Popen(cmd_netstat, stdout=subprocess.PIPE) | |
29 | |
30 occupied_ports = set() | |
31 for line in p1.stdout.read().split('\n'): | |
32 if line.startswith('tcp') or line.startswith('tcp6'): | |
33 col = line.split() | |
34 local_address = col[3] | |
35 local_port = local_address.split(':')[1] | |
36 occupied_ports.add(int(local_port)) | |
37 | |
38 # Generate random free port number. | |
39 while True: | |
40 port = random.randrange(range[0], range[1]) | |
41 if port not in occupied_ports: | |
42 break | |
43 return port |