Python PEXPECT中的循环行

Python PEXPECT中的循环行,python,pexpect,Python,Pexpect,我创建了一个名为“commands.txt”的txt文件,它包含两个命令(2行) 我想在交换机中运行这两个命令,但只执行一个命令。下面是我的脚本的样子: def shvlan(device,child): commandFile = open('commands.txt', 'r') commands = [i for i in commandFile] for command in commands: child.sendline(command)

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

我想在交换机中运行这两个命令,但只执行一个命令。下面是我的脚本的样子:

 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行吗?

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

 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    

胃口大开!!!!!正在执行多个命令…非常感谢。我们可以在列表中用逗号(,)分隔每一行吗?现在,它在列表中以两个元素的形式出现:uuuuuuuuu切换1#sh run vlan 158 uuuuuuuuo!命令:显示正在运行的配置vlan 158!时间:2018年7月19日星期四05:46:37(版本7.1)N1(1c)(虚拟局域网配置158)(虚拟局域网配置158)(名称营销)(模式制造路径)(交换机1)sh运行虚拟局域网159)!命令:显示正在运行的配置vlan 159!时间:2018年7月19日星期四05:46:42 \uuuuu版本7.1(4)N1(1c)\uuuuuuuu vlan配置159 \uuuuuuuuuuu vlan 159 \uuuuuuuu名称销售\uuuuuuu模式FabricPath每行以“\uuuuuuuuuuuu”开头是一个新行。我添加了“uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?
 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