V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fanhaipeng0403
V2EX  ›  Python

问大家一个关于 async 和 await 的问题, 新年快乐~

  •  
  •   fanhaipeng0403 · 2018-12-31 22:48:10 +08:00 · 1489 次点击
    这是一个创建于 2189 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问大家一个问题

        
        
    
    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)
    
    

    类似于这段代码。。

    2 条回复    2019-01-02 13:08:16 +08:00
    fanhaipeng0403
        1
    fanhaipeng0403  
    OP
       2018-12-31 22:48:40 +08:00
    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
    canwushuang
        2
    canwushuang  
       2019-01-02 13:08:16 +08:00
    协程在 loop 内部有效,遇到 io 阻塞则继续运行,而你那个是 loop 外。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   949 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 22:53 · PVG 06:53 · LAX 14:53 · JFK 17:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.