Search code examples
pythonpexpect

pexpect spawn in a function


pexpect.spawn seems to fail when I put it in a function. In the example below, I expect it to touch both '/tmp/no.txt' and '/tmp/yes.txt'. It only touches /tmp/yes.txt. I've tried all of the obvious locations for the 'import pexpect'. It doesn't throw errors, just doesn't run. Thanks for any suggestions!

import pexpect
def fun():
    import pexpect
    fail = pexpect.spawn('touch /tmp/no.txt')

fun()
succeed = pexpect.spawn('touch /tmp/yes.txt')

$ ls /tmp/*.txt
/tmp/yes.txt
$ 

Solution

  • You need to wait for the command run:

    import pexpect
    def fun():
        #import pexpect you've already imported pexpect you don't need to import it again 
        fail = pexpect.spawn('touch /tmp/no.txt')
        fail.wait()
    
    fun()
    succeed = pexpect.spawn('touch /tmp/yes.txt')
    succeed.wait()