如何字符串格式子进程输出?

时间:2017-11-15 14:09:03

标签: python python-3.x

下面是我在Python中使用subprocess模块的nslookup结果。

b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName:    
www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t  
216.58.197.68\r\n\r\n'

有人可以帮我格式化结果如下。

Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68

2 个答案:

答案 0 :(得分:1)

您可以通过将nslookup结果的行解析为字典,然后使用它来格式化输出来实现。

nslookup = (b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\n'
            b'Name: www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n'
            b'\t216.58.197.68\r\n\r\n')

info = {}
for line in nslookup.decode().splitlines():
    tokens = line.split()
    if len(tokens) == 2:
        if tokens[0] == 'Addresses:':
            info.setdefault('Addresses', []).append(tokens[1])  # Without ":"
        else:
            info[tokens[0].rstrip(':')] = tokens[1]
    elif len(tokens) == 1:
        info['Addresses'].append(tokens[0])

info['Addresses'] = ', '.join(info['Addresses'])  # Format and convert to string.

print('''\
Server: {Server}
Name: {Name}
DNS:  {Address}
Addresses: {Addresses}'''.format(**info))

输出:

Server: server.internal
Name: www.google.com
DNS:  192.168.0.2
Addresses: 2404:6800:4007:800::2004, 216.58.197.68

答案 1 :(得分:0)

您可以使用Python的unicode_escape来帮助转换它。然后可以将结果拆分成行并重新组装如下:

nslookup = b'Server:  server.internal\r\nAddress:  192.168.0.2\r\n\r\nName: www.google.com\r\nAddresses:  2404:6800:4007:800::2004\r\n\t216.58.197.68\r\n\r\n'
lines = [line.strip('\t').replace('  ', ' ') for line in nslookup.decode('unicode_escape').splitlines()]
print('\n'.join([lines[0], lines[3], lines[1], '{} , {}'.format(lines[4], lines[5])]))

给你:

Server: server.internal
Name: www.google.com
Address: 192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68

Address:可由DNS:替换为.replace()