保存文本fi的一部分

2024-06-29 00:57:35 发布

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

我使用Rancid服务器来保存有关网络上Cisco交换机的信息。我想编写一个python3脚本来将数据的配置部分提取到一个文本文件中。我已经让这个工作,但我有一个文件,其中有两次配置,我只想第一次配置。在

这就是我所做的:

import sys

flag = False

start = ('version', 'config-register')
end = ('@\n', 'monitor 6\n', 'end\n')

with open(sys.arbv[1], "r") as file:
         for line in file:

                   if line.startswith(start):
                           file = True;

                   if flag:
                           sys.stdout.write(line)

                   if line.endswith(end):
                           flag = False

有两次配置的文件使用'version'作为开始,使用'@\n'作为结束。我尝试过使用break,但是我仍然得到了这两个配置。在

文件示例: !VTP:VTP域名: !VTP:VTP修剪模式:禁用(操作禁用) !VTP:VTP V2模式:禁用 !VTP:VTP陷阱生成:禁用 !VTBE 0x57 0x05 0x5 0xBB:0x5 0xBB !VTP:VTP版本正在运行:1 ! !调试:调试级别设置为次要(1) !调试:新会话的默认日志记录级别:3 ! !核心:模块实例进程名PID Date(年-月-日-时) !核心:------------------------------------------------------------------------------ ! !进程日志:进程PID正常退出堆栈核心日志创建时间 !进程日志:------------------------------------------------------------------- ! 在

^{pr2}$

Tags: 文件false核心if进程versionsysline
1条回答
网友
1楼 · 发布于 2024-06-29 00:57:35

版本和配置寄存器的顺序在这里很重要。因此,您最好只迭代文件两次。你可以用这种方法把文件的各个部分分开。一次查找version的值,一次查找config register。在

import sys

flag = False

VERSION_NAME = r'version'

CONFIG_NAME = r'config-register'

end = ('@\n', 'monitor 6\n', 'end\n')

FILE_NAME = sys.argv[1]


# find the config-register
with open(FILE_NAME, "r") as file:
    start = CONFIG_NAME
    config_found = False

    for line in file:
        if line.startswith(start) and not config_found:
            flag = True                   # correction

        if flag:
            sys.stdout.write(line)
        if flag and line.endswith(end):
            print("Found Break")
            break                          # correction

        if line.startswith(start):
            config_found = True


# find the version
with open(FILE_NAME, "r") as file:
    start = VERSION_NAME
    config_found = False

    for line in file:
        if line.startswith(start) and not config_found:
            flag = True

        if flag:
            sys.stdout.write(line)

        if flag and line.endswith(end):
            print("Found Break")
            break

        if line.startswith(start):
            config_found = True

然后再循环一次,只搜索配置版本和“结束”。这不是最注重性能的,但是由于您没有处理整个文件,希望这能满足您的需要。在

相关问题 更多 >