Skip to main content
 首页 » 编程设计

python之产卵后向 pexpect child 发送更多命令

2024年11月01日12xxx_UU

我正在学习如何使用 pexpect。我的目标是获取目录列表,然后使用 pexpect 在另一个文件夹中重新创建这些目录。但是,如何在 python 循环中将多个命令发送到 pexpect 子项中? child.sendline() 对我不起作用 =[。我一直在重生 child ,但这似乎不是正确的做法。

import pexpect 
child = pexpect.spawn("""bash -c "ls ~ -l | egrep '^d'""") 
child.expect(pexpect.EOF) 
tempList = child.before 
tempList = tempList.strip() 
tempList = tempList.split('\r\n') 
listofnewfolders = [] 
for folder in tempList: 
    listofnewfolders.append(folder.split(' ')[-1]) 
for folder in listofnewfolders: 
    child.sendline("""bash -c 'mkdir {0}'""".format("~/newFolder/%s" % folder)) 

请您参考如下方法:

如果您执行 bash -c,bash 将运行您指定的命令,然后退出。要发送多个命令,您需要这样做:

p = pexpect.spawn('bash') 
p.expect(prompt_regex) 
p.sendline('ls')  # For instance 
p.expect(prompt_regex) 
print(p.before)  # Get the output from the last command.