如何解析子进程的结果
How to parse results from a subprocess
我正在尝试将从 netstat
获得的 Python 中的字符串传递给 awk 以用于构建新对象。
知道为什么这不起作用吗?请原谅可怕的编码,我今天才开始使用 Python 并尝试学习如何使用该语言。
class NetstatGenerator():
def __init__(self):
import subprocess
self.results = subprocess.Popen("netstat -anbp tcp", shell=True, stdout=subprocess.PIPE).stdout.read()
self.list = []
self.parse_results()
def parse_results(self):
lines = self.results.splitlines(True)
for line in lines:
if not str(line).startswith("tcp"):
print("Skipping")
continue
line_data = line.split(" ")
self.list.append(NetstatData(self.line_data[0], self.line_data[15], self.line_data[18], self.line_data[23]))
def get_results(self):
return self.list
class NetstatData():
def __init__(self, protocol, local_address, foreign_address, state):
self.protocol = protocol
self.local_address = local_address
self.foreign_address = foreign_address
self.state = state
def get_protocol(self):
return str(self.protocol)
def get_local_address(self):
return str(self.local_address)
def get_foreign_address(self):
return str(self.foreign_address)
def get_state(self):
return str(self.state)
data = NetstatGenerator()
抱歉,netstat
在 Linux 上不支持 -b
,而且我身边没有 BSD 盒子。
假设您有一个名为 netstat_output
的行列表,其中包含如下项目:
tcp 0 0 127.0.0.1:9557 127.0.0.1:56252 ESTABLISHED -
要解析一行,您 split()
它并在索引 0、3、4、5 处选择元素。
要存储项目,您不需要定义样板 holding class; namedtuple
为所欲为:
from collections import namedtuple
NetstatInfo = namedtuple('NetstatInfo',
['protocol', 'local_address', 'remote_address', 'state'])
现在你可以解析一行:
def parseLine(line):
fields = line.split()
if len(fields) == 7 and fields[0] in ('tcp', 'udp'):
# alter this condition to taste;
# remember that netstat injects column headers.
# consider other checks, too.
return NetstatInfo(fields[0], fields[3], fields[4], fields[5])
# otherwise, this function implicitly returns None
现在这样的事情一定是可能的:
result = []
for line in subprocess.Popen(...):
item = parseLine(line)
if line: # parsed successfully
result.append(line)
# now result is what you wanted; e.g. access result[0].remote_address
我正在尝试将从 netstat
获得的 Python 中的字符串传递给 awk 以用于构建新对象。
知道为什么这不起作用吗?请原谅可怕的编码,我今天才开始使用 Python 并尝试学习如何使用该语言。
class NetstatGenerator():
def __init__(self):
import subprocess
self.results = subprocess.Popen("netstat -anbp tcp", shell=True, stdout=subprocess.PIPE).stdout.read()
self.list = []
self.parse_results()
def parse_results(self):
lines = self.results.splitlines(True)
for line in lines:
if not str(line).startswith("tcp"):
print("Skipping")
continue
line_data = line.split(" ")
self.list.append(NetstatData(self.line_data[0], self.line_data[15], self.line_data[18], self.line_data[23]))
def get_results(self):
return self.list
class NetstatData():
def __init__(self, protocol, local_address, foreign_address, state):
self.protocol = protocol
self.local_address = local_address
self.foreign_address = foreign_address
self.state = state
def get_protocol(self):
return str(self.protocol)
def get_local_address(self):
return str(self.local_address)
def get_foreign_address(self):
return str(self.foreign_address)
def get_state(self):
return str(self.state)
data = NetstatGenerator()
抱歉,netstat
在 Linux 上不支持 -b
,而且我身边没有 BSD 盒子。
假设您有一个名为 netstat_output
的行列表,其中包含如下项目:
tcp 0 0 127.0.0.1:9557 127.0.0.1:56252 ESTABLISHED -
要解析一行,您 split()
它并在索引 0、3、4、5 处选择元素。
要存储项目,您不需要定义样板 holding class; namedtuple
为所欲为:
from collections import namedtuple
NetstatInfo = namedtuple('NetstatInfo',
['protocol', 'local_address', 'remote_address', 'state'])
现在你可以解析一行:
def parseLine(line):
fields = line.split()
if len(fields) == 7 and fields[0] in ('tcp', 'udp'):
# alter this condition to taste;
# remember that netstat injects column headers.
# consider other checks, too.
return NetstatInfo(fields[0], fields[3], fields[4], fields[5])
# otherwise, this function implicitly returns None
现在这样的事情一定是可能的:
result = []
for line in subprocess.Popen(...):
item = parseLine(line)
if line: # parsed successfully
result.append(line)
# now result is what you wanted; e.g. access result[0].remote_address