在Python Splitlines空的空间表(Splitlines in Python a tab

2019-10-19 01:59发布

通过一个命令Linux(lsof的),我得到表中的数据的一个系列:

COMMAND     PID       USER   FD      TYPE DEVICE  SIZE/OFF   NODE NAME
init          1       root  cwd   unknown                         /proc/1/cwd (readlink: Permission denied)
init          1       root  rtd   unknown                         /proc/1/root (readlink: Permission denied)
python    30077      user1  txt       REG    8,1   2617520 461619 /usr/bin/python2.6

我们可以看到有些地方emptly而言,我希望每一个细胞分裂成一个列表(每行一个列表)的方式,即时这样尝试:

lsof_list = commands.getoutput('lsof | sed \'1d\'')
k = 1
list_lsof = {}

j = 1
apps = {}

for line in lsof_list.splitlines():
    list_lsof[k] = line
    print(list_lsof[k])
    for apps[j] in list_lsof[k].split():
        #print(' app ', list_lsof[j])
        j += 1
        #print(apps[k])

        if j == 9:
            print(apps[1], apps[2], apps[3], apps[4], apps[5], apps[6], apps[7],apps[8])
            j = 1

但由于有不同的空间久,我得到了很多的emptly“”物品,我怎么能避免呢? 我想这个问题是在lsof_list.splitlines(),但我不能找到我需要改变。 谢谢!

Answer 1:

由于输出的每行几乎是固定宽度字段的记录,你可以做类似下面的解析它(这是基于什么是另一种答案我的)。 我所确定的字段中手动因为涉及自动确定它主要的困难的宽度由于左和右对齐字段的混合(以及孤独的可变长度一个在末端)。

import struct

lsof_list = """\
COMMAND     PID       USER   FD      TYPE DEVICE  SIZE/OFF   NODE NAME
init          1       root  cwd   unknown                         /proc/1/cwd (readlink: Permission denied)
init          1       root  rtd   unknown                         /proc/1/root (readlink: Permission denied)
python    30077      user1  txt       REG    8,1   2617520 461619 /usr/bin/python2.6
""".splitlines()

# note: variable-length NAME field at the end intentionally omitted
base_format = '8s 1x 6s 1x 10s 1x 4s 1x 9s 1x 6s 1x 9s 1x 6s 1x'
base_format_size = struct.calcsize(base_format)

for line in lsof_list:
    remainder = len(line) - base_format_size
    format = base_format + str(remainder) + 's'  # append NAME field format
    fields = struct.unpack(format, line)
    print fields

输出:

('COMMAND ', '   PID', '      USER', '  FD', '     TYPE', 'DEVICE', ' SIZE/OFF', '  NODE', 'NAME')
('init    ', '     1', '      root', ' cwd', '  unknown', '      ', '         ', '      ', '/proc/1/cwd (readlink: Permission denied)')
('init    ', '     1', '      root', ' rtd', '  unknown', '      ', '         ', '      ', '/proc/1/root (readlink: Permission denied)')
('python  ', ' 30077', '     user1', ' txt', '      REG', '   8,1', '  2617520', '461619', '/usr/bin/python2.6')


文章来源: Splitlines in Python a table with empty spaces