【问题标题】:Problem stripping characters from a pexpect query从 pexpect 查询中剥离字符的问题
【发布时间】:2021-11-26 20:27:20
【问题描述】:

我正在测试一个 python 脚本以从 Cisco 设备中检索软件版本。该脚本可以很好地连接到远程设备并获取所需的信息。当我尝试从 pexpect 输出中过滤一些不需要的信息时,问题就开始了。负责获取版本信息的函数代码如下:

def get_version_info(session):
    session.sendline('show version | include Version')
    result = session.expect(['>', pexpect.TIMEOUT])
    # Extract the 'version' part of the output
    version_output_lines = session.before.splitlines()
    version = version_output_lines[4].strip("'")
    print("--- got version: ", version)
    return version

拆分后的原始输出中所需的信息(代码中的第 5 行)放在以下列表中:

[b' ', b'', b'HOSTNAME#show version | include Version', b'Cisco IOS XE Software, Version 16.09.02', b'Cisco IOS Software [Fuji], ASR1000 Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Version 16.9.2, RELEASE SOFTWARE (fc4)', b'licensed under the GNU General Public License ("GPL") Version 2.0.  The', b'software code licensed under GPL Version 2.0 is free software that comes', b'GPL code under the terms of GPL Version 2.0.  For more details, see the', b'HOSTNAME#']

从上面的输出中我只需要“版本 16.9.2”,其余的都需要去掉。

我尝试隔离列表的第 4 个元素 (version_output_lines[4]) 并使用 strip 函数,但它一直发送错误:

TypeError: 需要一个类似字节的对象,而不是 'str'

所以我想知道您是否对如何从列表中删除所有不需要的信息并只保留前面提到的版本信息有更好的想法。

谢谢。

【问题讨论】:

    标签: python-3.x pexpect


    【解决方案1】:

    .strip() 方法适用于类型 strings 和类型 bytes。当应用于bytes 时,它需要一个bytes 参数而不是您提供的字符串"'"。所以使用.strip(b"'")

    您还可以决定让 pexpect 将字节编码为字符串,例如,在 spawn() 调用中使用 encoding='utf8' 作为参数。

    【讨论】:

    • 谢谢!仍在学习 pexpect 的基础知识。会试试的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 2010-09-19
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    相关资源
    最近更新 更多