Search code examples
pythonpexpect

When pexpect.spawn is called, does execution of the spawned program start immediately?


Are pexpect.spawn objects inactive until expect (or interact, send, etc) is called, or does the invoked process start immediately? For example:

import pexpect
process = pexpect.spawn("echo HELLO")
print ("Process created? Or run?")
process.expect("HELLO")

When the print statement occurs, has pexpect already run the echo command under the covers and is just holding off on letting it return until the expect call is processed? Or has nothing happened (echo hasn't run) until the first call to expect or similar?

Cheers


Solution

  • When passed a command, pexpect.spawn() forks and invokes the command immediately. The echo command in your example would have been run already.

    This is implied in the spawn constructor documentation:

    This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example::

    child = pexpect.spawn ('/usr/bin/ftp')
    child = pexpect.spawn ('/usr/bin/ssh [email protected]')
    child = pexpect.spawn ('ls -latr /tmp')
    

    You may also construct it with a list of arguments like so::

    child = pexpect.spawn ('/usr/bin/ftp', [])
    child = pexpect.spawn ('/usr/bin/ssh', ['[email protected]'])
    child = pexpect.spawn ('ls', ['-latr', '/tmp'])
    

    After this the child application will be created and will be ready to talk to.

    I've confirmed this by looking at the source code; the constructor calls _spawn() which is documented as follows:

    This starts the given command in a child process. This does all the fork/exec type of stuff for a pty. This is called by __init__. If args is empty then command will be parsed (split on spaces) and args will be set to parsed arguments.