首页   注册   登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python 学习手册
Python Cookbook
Python 基础教程
Python Sites
PyPI - Python Package Index
http://www.simple-is-better.com/
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
V2EX  ›  Python

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

  •  
  •   fanhaipeng0403 · 54 天前 · 732 次点击
    这是一个创建于 54 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问大家一个问题

        
        
    
    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
        1
    fanhaipeng0403   54 天前
    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
        2
    canwushuang   52 天前
    协程在 loop 内部有效,遇到 io 阻塞则继续运行,而你那个是 loop 外。
    关于   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   感谢   ·   实用小工具   ·   1688 人在线   最高记录 4385   ·  
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.3 · 20ms · UTC 16:31 · PVG 00:31 · LAX 08:31 · JFK 11:31
    ♥ Do have faith in what you're doing.
    沪ICP备16043287号-1