【问题标题】:Python Compare stringsPython比较字符串
【发布时间】:2015-09-22 09:29:29
【问题描述】:

我正在尝试比较 2 个字符串,一个来自 Pyserial,另一个是硬编码消息。它们似乎完全相同,但由于某种原因,函数 wait_prompt 只返回 0。

 def wait_prompt(device, msg):
        device.write("\n\n")
        device.flush()

        msg = msg + "\n"
        output = device.readline()

        print("\n")
        print("Looking for: " + msg + "|end")
        print("CLI shows: " + output + "|end")

        if output == msg:
                return 1
        return 0

def initialize_router(device):

        print ("Router connected on port " + port[0])

        while wait_prompt(device, "Would you like to enter the initial configuration dialog? [yes/no]: ") == 0:
                time.sleep(1)

        device.write("no\n")
        device.flush()

        while wait_prompt(device, "Line protocol on Interface Vlan1, changed state to up") == 0:
                time.sleep(1)

        time.sleep(2)
        device.write("\n")
        device.flush()

当我在做的时候,有没有更好的方法可以通过 consol 电缆与终端进行通信?我看到了 pexpect,但它似乎无法连续工作。

解决方案

问题是输出最后返回了 \r\r\n 而不仅仅是我期待的 \n。我修改了代码以仅搜索字符串的一部分来验证测试。这里是:

def wait_prompt(device, msg):
        device.write("\n\n")
        device.flush()
        output = device.readline()

        if msg in output:
                return 1
        return 0

def initialize_router(device):

        print ("Router connected on port " + port[0])

        while wait_prompt(device, "[yes/no]:") == 0:
                time.sleep(1)

        device.write("no\n")
        device.flush()

        while wait_prompt(device, "Line protocol on Interface Vlan1, changed state to up") == 0:
                time.sleep(1)

        time.sleep(2)
        device.write("\n")
        device.flush()

【问题讨论】:

  • 请将repr()type() 两个字符串的返回值添加到您的帖子中。
  • 感谢如果发现问题输出以 /r/r/n 结尾并且我的测试只是 /n 我修改了代码,而不是只测试字符串的一部分的完全匹配测试要在消息中,请参见上文
  • 我建议你要么删除问题,要么自己添加一个答案,然后你接受。

标签: python string terminal serial-port string-comparison


【解决方案1】:

问题是输出最后返回了 \r\r\n 而不仅仅是我期待的 \n。我修改了代码以仅搜索字符串的一部分来验证测试。这里是:

def wait_prompt(device, msg):
        device.write("\n\n")
        device.flush()
        output = device.readline()

        if msg in output:
                return 1
        return 0

def initialize_router(device):

        print ("Router connected on port " + port[0])

        while wait_prompt(device, "[yes/no]:") == 0:
                time.sleep(1)

        device.write("no\n")
        device.flush()

        while wait_prompt(device, "Line protocol on Interface Vlan1, changed state to up") == 0:
                time.sleep(1)

        time.sleep(2)
        device.write("\n")
        device.flush()

【讨论】:

    猜你喜欢
    • 2016-08-19
    • 2022-01-10
    • 2022-01-16
    • 2017-08-13
    • 2015-02-24
    • 2019-01-17
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多