在主代码执行开始之前,我想检查一个特定的端口是否打开......如果是......然后关闭端口,以便代码可以“干净地”启动。
所以我在网上搜索并在这里找到了代码: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[