python: 使用字段分隔符打印单列

python: print a single column using field separator

我是 python 的初学者。 从日志中,我希望使用 python 仅提取位于每行中间的主机名(在“command_wrappers INFO:”和“: pg_receivewal: 之间切换到timeline") 以便向这些服务器中的每一个发送命令。

日志行如下:

2020-07-16 10:13:03,065 [105879] barman.command_wrappers INFO: epgbd-b2bintraextranet: pg_receivewal: switched to timeline 13 at 1F/BC062600
2020-07-16 10:13:03,185 [105877] barman.command_wrappers INFO: epgbd-asteriaconnect: pg_receivewal: switched to timeline 3 at 8/C0066708
2020-07-16 10:13:03,341 [105881] barman.command_wrappers INFO: epgbd-comel: pg_receivewal: switched to timeline 5 at 50/6D04FB30
2020-07-16 10:13:03,352 [105884] barman.command_wrappers INFO: epgbd-dommages-ouvrages: pg_receivewal: switched to timeline 4 at 4C/2605C388
2020-07-16 10:13:03,726 [105888] barman.command_wrappers INFO: epgbd-efs: pg_receivewal: switched to timeline 3 at 50/8C067640

这是我正在寻找的结果:

epgbd-b2bintraextranet
epgbd-asteriaconnect
epgbd-comel
epgbd-dommages-ouvrages
epgbd-efs

有没有简单的方法可以得到这样的结果?

一般情况下,您通常会使用正则表达式来解决此类问题,但在您的情况下。您可以简单地使用 split() 方法。

如果你的情况看起来像:

>>mystr = "2020-07-16 10:13:03,065 [105879] barman.command_wrappers INFO: epgbd-b2bintraextranet: pg_receivewal: switched to timeline 13 at 1F/BC062600"
>>mystr.split(":")[3].strip()
>>'epgbd-b2bintraextranet'

如果日志与示例完全一致...