python-3.xpexpect

Convert Expect script to Pexpect to allow Enter key


I've a perfectly working expect script that I'm trying to convert to python using expect or subprocess. I've created it using autoexpect.

It just wait for password prompt and ignore it by pressing Enter key:

set timeout -1
spawn ./electron-cash --dir ""  create
match_max 100000
expect -exact "Password (hit return if you do not wish to encrypt your wallet):"
send -- "\r"
expect eof

However when I tried to do the same using pexpect I had all different type of issues. Either it stuck with no response or just shows nothing and close.

Here is what I came up with but it hangs doing nothing:

import pexpect 
import sys

python_exec = "/home/user/electron-cash-wallet/venv/bin/python"
command = "/home/user/electron-cash-wallet/src/Electron-Cash/electron-cash"


p = pexpect.spawn(python_exec, [command, "--scalenet", "create"])
# ~ p.logfile_read = sys.stdout.buffer 

p.expect("Password (hit return if you do not wish to encrypt your wallet):")

p.sendline(b'\r')

p.expect(pexpect.EOF)

I'm using Python 3


Solution

  • I've found a solution, it was an issue with commenting the parentheses in the expected message.

    Changed to this:

    p.expect("Password \(hit return if you do not wish to encrypt your wallet\):")
    

    Full code:

    import pexpect 
    import sys
    import os
    
    home_dir = os.path.expanduser('~')
    
    python_exec = home_dir + "/dev/electron-cash-wallet/venv/bin/python"
    command = home_dir + "/dev/electron-cash-wallet/src/Electron-Cash/electron-cash"
    network = "scalenet"
    
    
    p = pexpect.spawn(python_exec, [command, "--scalenet", "create"])
    # ~ p.logfile_read = sys.stdout.buffer 
    
    p.expect("Password \(hit return if you do not wish to encrypt your wallet\):")
    
    p.sendline(b'\r')
    
    p.expect(pexpect.EOF)
    
    

    Here is a more advanced and verbose version in function:

    import pexpect 
    import sys
    import os
    
    home_dir = os.path.expanduser('~')
    
    python_exec = home_dir + "/electron-cash-wallet/venv/bin/python"
    ec_exec = home_dir + "/electron-cash-wallet/src/Electron-Cash/electron-cash"
    network = "scalenet"
    
    def create_wallet(python_exec, ec_exec, network):
        print("Python: ", python_exec)
        print("Electron Cash: ", ec_exec)
        # Execute the command
        p = pexpect.spawn(python_exec, [ec_exec, f"--{network}", "create"])
        # Verbose, show messages
        p.logfile_read = sys.stdout.buffer
        p.delaybeforesend = 2
        print("Exceution done")
        # Expect the response
        p.expect("Password \(hit return if you do not wish to encrypt your wallet\):")
        print("Expected input received")
        p.delaybeforesend = 1
        # Send return key
        p.sendline(b'\r')
        print("Sent response")
        p.expect(pexpect.EOF)
        print("Script done")
    
    create_wallet(python_exec, ec_exec, network)