繁体   English   中英

遍历机器人框架中的列表

[英]Iterating through a list in robot framework

我有以下文本文件。

[box_1]
show ethernet 
show adjacency
show log
[box_2]
run ethernet 
run adjacency
show log

我需要编写一个机器人文件,如果遇到[box_1],它将在其中运行,

run ethernet 
run adjacency
show log

如果遇到[box_2],它将在该命令下运行以下命令。

这是我的机器人代码:

${File}=    Get File  Resources\\Source\\textfile.txt
@{list}=    Split to lines  ${File}    
Log    ${list}
${op}=    Get From List ${list}    0    
log    ${op}
${first_line}=    Get Slice From List   ${list}    1
:FOR    ${line}    IN    @{first_line}
\   ${result}=    Run Keyword If    '${op}'=='[${box_1}]' and     run_command    ${line}
\   ${result}=    Run Keyword If    '${op}'=='[${box_2}]' and     run_command    ${line}

但它仅用于标识[box_1]而不会转到[box_2]。 并且命令后面可以有多个框。 有人可以帮忙吗?

谢谢。

您只分配一次${op}

${op}= Get From List ${list} 0

永远不要改变它。 这就是为什么它始终为[box_1]而从不成为[box_2] 您必须将赋值放入FOR -loop并更改其余代码,以便执行不同box -es之间的命令。

尽管@Psytho是正确的,但不足以解决问题。

在下面的示例中,我添加了必需的库和自定义关键字来模仿运行命令Operatingsystem关键字。

在此示例中,我跳过标题并执行命令。 以类似的方式,您可以使用${match[0]}来了解哪个标题当前处于活动状态,并在确定操作时使用它。

*** Settings ***
Library    String    
Library    Collections
Library    OperatingSystem    

*** Test Cases ***
TC v1
    ${File}=    Get File  textfile.txt
    @{lines}=    Split to lines  ${File}    

    :FOR    ${line}    IN    @{lines}
    \    ${match}  Get Regexp Matches    ${line}    \\[(.*)\\]    1
    \    ${count}  Get Length    ${match}
    \    ${result}  Run Keyword If    ${count} == 0    run_custom_command    ${line}  
TC v2
    @{commands}    Get Commands    box_2    textfile.txt
    :FOR    ${command}    IN    @{commands}
    \    run_custom_command    ${command}    

    @{commands}    Get Commands    box_1    textfile.txt
    :FOR    ${command}    IN    @{commands}
    \    run_custom_command    ${command}       

*** Keywords ***
Run Custom Command
    [Arguments]    ${command}
    Log    Run Command: ${command}
    [return]    SUCCESS

Get Commands
    [Arguments]    ${ENV}    ${filepath}
    ${string}=    Get File            ${filepath}
    ${match}=     Get Regexp Matches  ${string}    \\[${ENV}\\]\\n((.|\\n)*?)(\\[|$)    1
    @{lines}=     Split to lines   ${match[0]}
    [Return]    ${lines}

编辑:添加了仅依赖于正则表达式的第二个选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM