在主代码执行开始之前,我想检查特定端口是否打开..如果是..然后关闭端口,以便代码可以“干净地”启动。
所以我在网上谷歌找到了代码: http://www.paulwhippconsulting.com.au/tips/63-finding-and-killing-processes-on-ports
但是只是从那里粘贴代码:
import os
import subprocess
import re
ports = ['1234','5678','9101']
popen = subprocess.Popen(['netstat', '-lpn'],
shell=False,
stdout=subprocess.PIPE)
(data, err) = popen.communicate()
pattern = "^tcp.*((?:{0})).* (?P[0-9]*)/.*$"
pattern = pattern.format(')|(?:'.join(ports))
prog = re.compile(pattern) #<---- error line
for line in data.split('\n'):
match = re.match(prog, line)
if match:
pid = match.group('pid')
subprocess.Popen(['kill', '-9', pid])
但它会引发错误。
raise error, v # invalid expression
sre_constants.error: unknown specifier: ?P[
答案 0 :(得分:4)
发布该片段的人忘记了HTML - 逃避他的代码!正确的代码如下:
import os
import subprocess
import re
ports = ['1234','5678','9101']
popen = subprocess.Popen(['netstat', '-lpn'],
shell=False,
stdout=subprocess.PIPE)
(data, err) = popen.communicate()
pattern = "^tcp.*((?:{0})).* (?P<pid>[0-9]*)/.*$"
pattern = pattern.format(')|(?:'.join(ports))
prog = re.compile(pattern)
for line in data.split('\n'):
match = re.match(prog, line)
if match:
pid = match.group('pid')
subprocess.Popen(['kill', '-9', pid])
请注意<pid>
跟在?P
。