Search code examples
pythonshellpexpect

Python pexpect not working as expected


Im trying to write a program that runs some shell commands wit emulated user data.

The problem is that the shell command does not run correctly without this line in the end of the code:

raw_input('press <enter> to exit')

How can i get rid of that line?

child = pexpect.spawn('grunt init:gruntfile')
child.logfile_read = sys.stdout

child.expect ('Is the DOM involved in ANY way?')
child.sendline ('y')
child.logfile_read = sys.stdout

child.expect ('Will files be concatenated or minified?')
child.sendline ('y')
child.logfile_read = sys.stdout

child.expect ('Will you have a package.json file?')
child.sendline ('y')
child.logfile_read = sys.stdout

child.expect ('Do you need to make any changes to the above before continuing?')
child.sendline ('n')
child.logfile_read = sys.stdout

raw_input('press <enter> to exit')

Solution

  • The problem appears to be that without the raw_input to slow the program down, your python script is exiting before the child process is finished (and killing the child process in the process).

    I think pexpect.wait() is supposed to handle this situation, but it sounds from the documentation like wait() will hang if there is unread output after the child process exits, and without knowing the details of your child process I can't say whether or not there is a risk that will happen. Some combination of read() and wait() might work, or if it's too much trouble to figure that out you could just time.sleep() a number of seconds.