sending more commands to pexpect child after spawn

4.6k Views Asked by At

I am learning how to use pexpect. My goal is getting a list of directories, then recreate those directory in another folder by using pexpect. However, how do I send multiple of commands into a pexpect child in a python loop? child.sendline() doesnt work for me =[. I have been respawning the child, but that doesnt seem like the proper way of doing it.

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

There are 1 best solutions below

0
On

If you do bash -c, bash will run the command you specify, and then exit. To send multiple commands, you'll need to do it like this:

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.