Wexpect freezes at spawn() method

589 Views Asked by At

When I run the example code from wexpect, it freezes on the spawn method.

import wexpect
prompt = '[A-Z]\:.+>'

child = wexpect.spawn('cmd.exe')
child.expect(prompt)  # Wait for startup prompt

child.sendline('dir')  # List the current directory
child.expect(prompt)

print(child.before)  # Print the list
child.sendline('exit')

I found out that method connect_to_child in wexpect (code below copied from the repository) causes the problem. It keeps throwing "no pipe" exception, and gets stuck in a never-ending loop.

def connect_to_child(self):
    pipe_name = 'wexpect_{}'.format(self.console_pid)
    pipe_full_path = r'\\.\pipe\{}'.format(pipe_name)
    logger.debug(f'Trying to connect to pipe: {pipe_full_path}')
    while True:
        try:
            self.pipe = win32file.CreateFile(
                pipe_full_path,
                win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                0,
                None,
                win32file.OPEN_EXISTING,
                0,
                None
            )
            logger.debug('Pipe found')
            res = win32pipe.SetNamedPipeHandleState(self.pipe, win32pipe.PIPE_READMODE_MESSAGE,
                                                    None, None)
            if res == 0:
                logger.debug(f"SetNamedPipeHandleState return code: {res}")
            return
        except pywintypes.error as e:
            if e.args[0] == winerror.ERROR_FILE_NOT_FOUND:      # 2
                logger.debug("no pipe, trying again in a bit later")
                time.sleep(0.2)
            else:
                raise

I'm using windows 10, python 3.9.1 and wexpect 4.0.0

1

There are 1 best solutions below

0
amks1 On

I was facing the same problem. I did some trial and error and found that wexpect doesn't work inside a virtual environment. Deactivate the virtual environment, and it should work.