带有 Python 的机器人框架关键字:不匹配的字符串或 IP 出错。如何解决这个问题?

Robot Framework Keyword with Python: Error with unmatched string or IP. How to fix this?

我正在尝试为 Robot Framework 写一个关键字,正如@Brayan Oakley 在问题中建议的那样:

我的 Python 文件:

import os,re

def check_IP():
    cmd = ' netstat -ano '
    output = os.popen(cmd).read()
    match1 = re.findall('.* (1.1.1.1).*',output)
    mat1 = ['1.1.1.1']
    if match1 == mat1:
        print "IP addr found"
    if match1 != mat1:
        raise Exception('No matching IP...')

check_IP()

我正在尝试匹配 "netstat -ano" 命令中的 IP 地址。如果匹配,我将按预期收到 "IP addr found" 消息。

但如果未找到 IP 地址,我会收到预期的异常,但会出现以下错误消息。

C:\Users\test\Desktop>python check.py
Traceback (most recent call last):
  File "check.py", line 13, in <module>
    check_IP()
  File "check.py", line 11, in check_IP
    raise Exception('No matching IP...')
Exception: No matching IP...

C:\Users\test\Desktop>

有解决这个问题的线索吗?

代码完全按照您的指示执行。你是 运行 机器人上下文之外的代码,这就是 python 处理异常的方式。

如果您不想看到堆栈跟踪,请捕获异常并打印您想要的任何消息。

    try:
        check_IP()
    except Exception as e
        print str(e)

当然,如果您使用 check_IP 作为关键字,您会希望删除所有这些代码。

使用以下机器人文件:

*** Settings ***
Documentation   Test Stability Tests
Library        Network.py

*** Test Cases ***
Test: Test Robot File
    Check Network Status

使用以下Python文件

import os, re
def check_network_status():
    cmd = ' netstat -ano '
    output = os.popen(cmd).read()
    match1 = re.findall('.* (1.1.1.1).*',output)
    mat1 = ['1.1.1.1']
    if match1 == mat1:
        print("IP Address found")
    elif match1 != mat1:
        raise AssertionError("IP Address not Found")

注意:不要调用Python文件中的函数。 只需在 python 文件中创建 类 和函数(如果您以后想要的话)。 他们会在 运行 时间自动取消。