Python读取文件和d的显示块

2024-06-26 00:06:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试阅读文件(示例如下)。 我需要显示两组不同的数据

  1. 第一个数据不是串联的(即不是连续的-分散在文本文件中)

我需要显示的行应该有我在searchstrings中查找的字符串

def basic():
    searchstrings = ['Device name:', 'Switch type is', 'Kernel uptime is' , 'NXOS: version' ] 
    for line in fh:
        for word in searchstrings:
            if word in line:
                print line

我上面代码的问题是多行显示如下:

NXOS: version 5.2
Device name: N11k
Kernel uptime is 55 day(s), 23 hour(s), 53 minute(s), 11 second(s)
NXOS: version 5.2
Device name: N11k
Kernel uptime is 55 day(s), 23 hour(s), 53 minute(s), 12 second(s)
Switch type is : Nexus1100 (8 Slot) Chassis

我想我的for循环逻辑不正确-需要帮助来修复它。 是否可以将行保存在变量中,以便以后打印?在

  1. 第二个数据是串联的(连续块) 我想从“显示模块”一直读到“显示许可证”上面的行 我试过这里列出的建议-python - Read file from and to specific lines of text 但没能成功-我根本没有产出

谢谢, 维克托

正在读取的文件:

Software
BIOS: version 06.20
NXOS: version 5.2
BIOS compile time: 11/07/2013
NXOS image file is: bootflash:///n1000-dk9.5.2.bin
NXOS compile time: 6/3/2014 13:00:00 [06/18/2014 23:35:53]

Hardware
cisco Nexus1000 C1508 (8 Slot) Chassis ("Supervisor Module")
Intel(R) Xeon(R) CPU E5-2403 with 16402460 kB of memory.
Processor Board ID SAL

Device name: N1k-LabSystem
bootflash: 21 kB
Kernel uptime is 55 day(s), 23 hour(s), 53 minute(s), 11 second(s)

Last reset
Reason: Unknown
System version: 5.2
Service:

Switch type is : Nexus1100 (8 Slot) Chassis

show module
Mod Ports Module-Type Model Status


2 52 48x1/10G SFP+ 4x40G Ethernet Module N11K-X9564PX ok
3 36 36p 40G Ethernet Module N11k-X9636PQ ok
21 0 Fabric Module N11k-FM ok
22 0 Fabric Module N11k-FM ok
23 0 Fabric Module N11k-FM ok
24 0 Fabric Module N11k-FM ok
25 0 Fabric Module N11k-FM ok
26 0 Fabric Module N11k-FM ok
27 0 Supervisor Module N11k-SUP-A active *
29 0 System Controller N11k-SC-A active
30 0 System Controller N11k-SC-A standby

Mod Sw Hw Slot


2 5.2 1.0 LC2
3 5.2 1.0 LC3
21 5.2 1.1 FM1
22 5.2 1.1 FM2

'show license'
XYZABNCD


Tags: 数据nameisversiondeviceokkernelfabric
1条回答
网友
1楼 · 发布于 2024-06-26 00:06:23

问题出在您的basic函数之外。我试过了,但线条没有重复。它可能只来自你所说的方式。如果您希望以后继续打印,请写下:

基本定义(fh): 结果=[] searchstrings=['设备名称:','开关类型为','内核正常运行时间为','NXOS:version'] 对于fh中的线路: 对于搜索字符串中的单词: 如果单词在行中: 结果追加(线条条()) 打破 返回结果

这样的话:

  • 即使该行包含多个搜索词,也只能执行一次
  • 将fh作为参数传递,而不是使用全局
  • 返回匹配行的列表

要获取show moduleshow license之间的行,可以使用:

def between(fh, first, last)
    ok = False
    for line in fh:
        if last in line: break
        if ok: print line.rstrip()
        if first in line: ok=True

between('show module', 'show license')

相关问题 更多 >