-1

在主代码执行开始之前,我想检查一个特定的端口是否打开......如果是......然后关闭端口,以便代码可以“干净地”启动。

所以我在网上搜索并在这里找到了代码: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[
4

1 回答 1

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.

于 2013-02-16T06:51:36.403 回答