Before the main code execution starts, I want to check if a particular port is open or not.. and if it is.. then close the port so that code can start “cleanly”.
So I google online and found the code here: http://www.paulwhippconsulting.com.au/tips/63-finding-and-killing-processes-on-ports
But just pasting the code from there:
JavaScript
x
21
21
1
import os
2
import subprocess
3
import re
4
5
ports = ['1234','5678','9101']
6
7
8
popen = subprocess.Popen(['netstat', '-lpn'],
9
shell=False,
10
stdout=subprocess.PIPE)
11
(data, err) = popen.communicate()
12
13
pattern = "^tcp.*((?:{0})).* (?P[0-9]*)/.*$"
14
pattern = pattern.format(')|(?:'.join(ports))
15
prog = re.compile(pattern) #<---- error line
16
for line in data.split('n'):
17
match = re.match(prog, line)
18
if match:
19
pid = match.group('pid')
20
subprocess.Popen(['kill', '-9', pid])
21
But it throws an error.
JavaScript
1
3
1
raise error, v # invalid expression
2
sre_constants.error: unknown specifier: ?P[
3
Advertisement
Answer
The fellow who posted that snippet forgot to HTML-escape his code! The correct code is as follows:
JavaScript
1
21
21
1
import os
2
import subprocess
3
import re
4
5
ports = ['1234','5678','9101']
6
7
8
popen = subprocess.Popen(['netstat', '-lpn'],
9
shell=False,
10
stdout=subprocess.PIPE)
11
(data, err) = popen.communicate()
12
13
pattern = "^tcp.*((?:{0})).* (?P<pid>[0-9]*)/.*$"
14
pattern = pattern.format(')|(?:'.join(ports))
15
prog = re.compile(pattern)
16
for line in data.split('n'):
17
match = re.match(prog, line)
18
if match:
19
pid = match.group('pid')
20
subprocess.Popen(['kill', '-9', pid])
21
Note that <pid>
follows the ?P
.