Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Hands on the Python Library pexpect

Tips and Traps

  1. The command-line tool of some (e.g., network) applications might be slow to authenticate. If you use pexect to automate such a command-line tool, it is best to wait for sometime after sending password using child.sendline(passwd). If the authentication has ouput on both success and failure, a smart way is to wait for the success or failure message to come out.

     child.expect(".*success_pattern.*|.*failure_pattern.*")
    
    

    If the the output of authentication contains the same keyword (e.g., dclong) on both success and failure, the pattern can be further simplified.

     child.expect(".*dclong.*")
  2. The method spawn.interact gives control of the child process back to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This is extremely useful if you only want pexpect to hijack the child process for certain interactions. For example, if a command-line tool requires both a password and a hardware token for authentication, you can use pexpect to hijack the child process to enter password automatically and then give control of the child process back to the user to authenticate using hard token.

In [ ]:

Comments