Python PEXPECT中的循环线

时间:2018-07-18 13:32:40

标签: python pexpect

我创建了一个名为“ commands.txt”的txt文件,其中包含两个命令(两行)

sh run vlan 158   
sh run vlan 159

我想在一个开关中运行这两个命令,但是只有一个命令被执行。这是我的脚本的样子:

 def shvlan(device,child):  
   commandFile = open('commands.txt', 'r') 
   commands = [i for i in commandFile]  
   for command in commands:  
    child.sendline(command)  
    child.expect('.*#')  
    vlans = child.after  
    child.close()  
    print device + ' conn closed'  
    print 'sh run vlan executed'  
    print vlans  
    return vlans                                                                          

有人建议为什么只占用.txt文件的第一行吗?

1 个答案:

答案 0 :(得分:0)

您正在关闭循环内的连接。您必须在循环后移动那部分代码。试试这样的东西

 def shvlan(device,child):
     vlans = []
     with open('commands.txt', 'r') as commands: 
         for command in commands:  
             child.sendline(command)  
             child.expect('.*#')  
             vlans.extend(child.after.splitlines())  

     child.close()  
     print device + ' conn closed'  
     print 'sh run vlan executed' 
     print vlans  
     return vlans