我正在尝试使用Pexpect异步期望(python 3.5.1和github的pexpect)从网络设备中收集一些信息来编写脚本并得到一些奇怪的东西:一切都可以正常使用多个设备并且不能用于更多(通常> 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())
如果我尝试使用范围(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:
...
为什么会这样?如何使用async pexpect编写工作脚本?
---------------回答------------
这是一个错误https://github.com/pexpect/pexpect/issues/347。现在pexpect命令修复了它。