2

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

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))
4

1 回答 1

2

如果这样做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.
于 2013-10-28T01:08:39.620 回答