簡體   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