Pexpect:具有多个连接的异步期望

Pexpect: async expect with several connection


我正在尝试使用 Pexpect async expect(python 3.5.1 and pexpect from github) 编写脚本以从网络设备收集一些信息并得到一些奇怪的东西:所有设备都可以正常工作并且不能'与更多人一起工作(通常 > 5-6)。我写了这个简单的测试脚本:

@asyncio.coroutine
def test_ssh_expect_async(num):
    print('Task #{0} start'.format(num))
    p = pexpect.spawn('ssh localhost', encoding='utf8')
    #p.logfile = sys.stdout
    yield from p.expect('password', async=True)
    p.sendline('***')
    yield from p.expect(r'@self-VirtualBox\:', async=True)
    p.sendline('uptime')
    yield from p.expect(r'@self-VirtualBox\:', async=True)
    p.sendline('uname -a')
    yield from p.expect(r'@self-VirtualBox\:', async=True)
    p.sendline('ll')
    yield from p.expect(r'@self-VirtualBox\:', async=True)
    print('Task #{0} end'.format(num))

@asyncio.coroutine
def test_loop():
    tasks = []
    for i in range(1, 5):
        tasks.append(test_ssh_expect_async(i))
    yield from asyncio.wait(tasks)
    print('All Tasks done')


print('--------------Async--------------------')

loop = asyncio.get_event_loop()
loop.run_until_complete(test_loop())

如果我尝试使用 range(1,3) 作为示例,我会得到:

self@self-VirtualBox:/media/sf_netdev$ python3 simple-test.py 
--------------Async--------------------
Task #3 running
Task #1 running
Task #2 running
Task #3 closed
Task #1 closed
Task #2 closed
All Tasks done

但是如果我增加上限,我会得到一些错误:

self@self-VirtualBox:/media/sf_netdev$ python3 simple-test.py 
--------------Async--------------------
Task #3 running
Task #1 running
Task #4 running
Task #2 running
Exception in callback BaseSelectorEventLoop.add_reader(11, <bound method...d=11 polling>>)
handle: <Handle BaseSelectorEventLoop.add_reader(11, <bound method...d=11 polling>>)>
Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/selector_events.py", line 234, in add_reader
    key = self._selector.get_key(fd)
  File "/usr/lib/python3.5/selectors.py", line 191, in get_key
    raise KeyError("{!r} is not registered".format(fileobj)) from None
KeyError: '11 is not registered'

During handling of the above exception, another exception occurred:
...

为什么会这样?如何使用异步预期编写工作脚本?

----------------答案------------

这是一个错误 https://github.com/pexpect/pexpect/issues/347。现在 pexpect 命令修复了它。

这是一个错误 https://github.com/pexpect/pexpect/issues/347。现在 pexpect 命令修复了它。