Python中关于async和await的问题请教

问大家一个问题

    

try: # pylint: disable=invalid-name asyncio_run = asyncio.run # type: ignore except AttributeError: _T = TypeVar(’_T’)

def asyncio_run(main: Awaitable[_T], *, debug: bool = False) -> _T:
    """Minimal re-implementation of asyncio.run (since 3.7)."""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.set_debug(debug)
    try:
        return loop.run_until_complete(main)
    finally:
        asyncio.set_event_loop(None)
        loop.close()

async def setup_and_run_hass(config_dir: str, args: argparse.Namespace) -> int: “”“Set up HASS and run.”"" from homeassistant import bootstrap, core

hass = core.HomeAssistant()

if args.demo_mode:
    config = {
        'frontend': {},
        'demo': {}
    }  # type: Dict[str, Any]
    bootstrap.async_from_config_dict(
        config, hass, config_dir=config_dir, verbose=args.verbose,
        skip_pip=args.skip_pip, log_rotate_days=args.log_rotate_days,
        log_file=args.log_file, log_no_color=args.log_no_color)
else:
    config_file = ensure_config_file(config_dir)
    print('Config directory:', config_dir)
    await bootstrap.async_from_config_file(
        config_file, hass, verbose=args.verbose, skip_pip=args.skip_pip,
        log_rotate_days=args.log_rotate_days, log_file=args.log_file,
        log_no_color=args.log_no_color)

if args.open_ui:
    # Imported here to avoid importing asyncio before monkey patch
    from homeassistant.util.async_ import run_callback_threadsafe

    def open_browser(_: Any) -> None:
        """Open the web interface in a browser."""
        if hass.config.api is not None:
            import webbrowser
            webbrowser.open(hass.config.api.base_url)

    run_callback_threadsafe(
        hass.loop,
        hass.bus.async_listen_once,
        EVENT_HOMEASSISTANT_START, open_browser
    )

return await hass.async_run()



exit_code = asyncio_run(setup_and_run_hass(config_dir, args))
if exit_code == RESTART_EXIT_CODE and not args.runner:
    try_to_restart()

这里的 exit_code = asyncio_run(setup_and_run_hass(config_dir, args)) 作用是什么,怎么感觉还是要等 setup_and_run_hass 跑完了才继续运行

就是针对一个函数使用 async 的目的,

import  asyncio

try: # pylint: disable=invalid-name asyncio_run = asyncio.run # type: ignore except AttributeError:

def asyncio_run(main,  debug=False):
    """Minimal re-implementation of asyncio.run (since 3.7)."""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.set_debug(debug)
    try:
        return loop.run_until_complete(main)
    finally:
        asyncio.set_event_loop(None)
        loop.close()

async def slow_operation_1(m): await asyncio.sleep(m) print(‘Slow operation {} complete’.format(m)) return m

async def slow_operation_2(n): await asyncio.sleep(n) print(‘Slow operation {} complete’.format(n))

return await slow_operation_1(m=n+1)

result = asyncio_run(slow_operation_2(2))

print(result)

类似于这段代码。。


Python中关于async和await的问题请教

3 回复

我无法理解你的问题


In [1]: import asyncio
…:
…: try:
…: # pylint: disable=invalid-name
…: asyncio_run = asyncio.run # type: ignore
…: except AttributeError:
…:
…: def asyncio_run(main, debug=False):
…: “”“Minimal re-implementation of asyncio.run (since 3.7).”""
…: loop = asyncio.new_event_loop()
…: asyncio.set_event_loop(loop)
…: loop.set_debug(debug)
…: try:
…: return loop.run_until_complete(main)
…: finally:
…: asyncio.set_event_loop(None)
…: loop.close()
…:
…: async def slow_operation_1(m):
…: await asyncio.sleep(m)
…: print(‘Slow operation {} complete’.format(m))
…: return m
…:
…:
…:
…: async def slow_operation_2(n):
…: await asyncio.sleep(n)
…: print(‘Slow operation {} complete’.format(n))
…:
…: return await slow_operation_1(m=n+1)
…:
…: result = asyncio_run(slow_operation_2(2))
…:
…: print(result)
…:

Slow operation 2 complete
Slow operation 3 complete
3

协程在 loop 内部有效,遇到 io 阻塞则继续运行,而你那个是 loop 外。

回到顶部