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
soratadori
V2EX  ›  Python

asyncio 可以指定协程的数量吗?

  •  
  •   soratadori · 2017-01-25 05:13:13 +08:00 · 2505 次点击
    这是一个创建于 2656 天前的主题,其中的信息可能已经有所发展或是发生改变。
    举个例子,有一个列表[1,2,3,……,m]
    
    如何让他一次“同时”输出 n 个?
    
    比如
    1
    1
    1
    
    2
    2
    2
    
    3
    3
    3
    
    4
    4
    4
    
    5
    5
    5
    
    下面这个要输出几次,就创建几个实例的写法感觉太笨了,也不好维护,有没有灵活的方法?
    当然,这个例子有点傻,因为执行过的没必要再执行一次。实际情况应该是如何根据队列灵活的调整执行速度。
    
    import asyncio
    
    li = [1,2,3,4,5,6,7,8,9,10]
    
    def hello():
        for i in li:
            print(str(i)+"\n")
    
    async def main():
        loop = asyncio.get_event_loop()
        future1 = loop.run_in_executor(None, hello)
        future2 = loop.run_in_executor(None, hello)
        future3 = loop.run_in_executor(None, hello)
        await future1
        await future2
        await future3
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    
    第 1 条附言  ·  2017-01-25 16:30:05 +08:00
    解决了...
    2 条回复    2017-02-09 15:55:53 +08:00
    Septembers
        1
    Septembers  
       2017-01-25 06:11:25 +08:00 via iPhone
    令牌桶?
    Lemon23
        2
    Lemon23  
       2017-02-09 15:55:53 +08:00
    楼主后来怎么解决的?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2624 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:06 · PVG 22:06 · LAX 07:06 · JFK 10:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.