netdev lib协同例程异常

时间:2020-02-04 14:21:12

标签: python-3.x async-await python-asyncio

我已经尝试了netdev lib一段时间了,下面的程序由于以下异常而无法正常工作:

回溯(最近通话最近): 文件“ D:/Code/async_npa/async_npa.py”,第93行,在 r = asyncio.run(main(dev_data())) 文件“ C:\ Users \ omera \ AppData \ Local \ Programs \ Python \ Python38-32 \ lib \ asyncio \ runners.py”, 43行 return loop.run_until_complete(main) 文件“ C:\ Users \ omera \ AppData \ Local \ Programs \ Python \ Python38-32 \ lib \ asyncio \ base_events.py”, 第612行,在run_until_complete中 返回future.result() 主文件中的文件“ D:/Code/async_npa/async_npa.py”,第88行 结果=等待asyncio.gather(任务中的任务在任务中) 文件“ D:/Code/async_npa/async_npa.py”,第88行,在 结果=等待asyncio.gather(任务中的任务在任务中) RuntimeError:任务的产量不好: sys:1:RuntimeWarning:从未等待协程'device_connection'

我还尝试使用asyncio的旧语法创建事件循环和任务,但仍然没有运气

代码块:

from jinja2 import Environment, FileSystemLoader
import yaml
import asyncio
import netdev


def j2_command(file_name: dict = 'script.j2', directory: str = '.') -> dict:
    env = Environment(loader=FileSystemLoader(directory))
    temp = env.get_template(file_name)
    temp_1 = temp.render()
    temp_1 = temp_1.split('\n')
    return temp_1


def get_host_name(open_connection) -> str:
    hostname = open_connection.base_prompt()
    hostname = hostname.split('#')[0]
    return hostname


def write_to_file(data, dev_conn):
    with open(f'./output/config_{get_host_name(dev_conn)}.txt', 'w') as conf:
        conf.write(data)


def load_yml(yaml_file='inventory.yml'):
    with open(yaml_file) as f:
        host_obj = yaml.safe_load(f)
    return host_obj


async def device_connection(connect_param):
    dev_connect = netdev.create(**connect_param)
    await dev_connect.connect()
    commands = j2_command()
    output = [f'\n\n\n\n\n##########################  1'
              f'  ##########################\n\n\n\n\n']

    for command in commands:
        breaker = f'\n\n\n\n\n##########################  {command}  ##########################\n\n\n\n\n'
        command_result = await dev_connect.send_command(command)
        output.append(breaker + command_result)
    await dev_connect.disconnect()
    output_result_string = "\n\n".join(output)
    return output_result_string


def dev_data():
    device_data = []
    # devices_names = []
    host_obj = load_yml()

    generic_data = host_obj[0]['generic_data']
    generic_username = generic_data['username']
    generic_password = generic_data['password']
    devices = host_obj[0]['devices']
    device_type = generic_data['device_type']
    device_secret = generic_data['secret']
    for device in devices:
        device_ip = device['ip_address']
        try:
            if device["username"]: generic_username = device['username']
            if device['password']: generic_password = device['password']
            if device["device_type"]: device_type = device['device_type']
            if device['secret']: device_secret = device['secret']

        except:
            pass

        dev = {
            'device_type': device_type,
            'host': device_ip,
            'username': generic_username,
            'password': generic_password,
            'secret': device_secret
        }
        print(dev)

        device_data.append(dev)

    return device_data


async def main(device_data):
    tasks = [device_connection(dev) for dev in device_data]
    result = await asyncio.gather(task for task in tasks)
    return result


if __name__ == '__main__':
    r = asyncio.run(main(dev_data()))
    print(r)

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

对不起,我的回复很晚,但希望对您有所帮助。似乎您在执行任务时遇到问题。

您可以定义一个全局device_connection()变量,而不是在output_result_string中返回结果,并将其附加到每个任务中。这样,您不必在main()

中收集任何东西

然后将main()更改为run(),如下所示:

async def run(device_data):
    tasks = [device_connection(dev) for dev in device_data]
    await asyncio.wait(tasks)

并在您的主要代码块中启动它:

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())

这是文档链接:netdev example link