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

asyncio 如何与 gui 程序结合使用?

  •  
  •   jander · 2014-05-13 15:43:48 +08:00 · 4064 次点击
    这是一个创建于 3629 天前的主题,其中的信息可能已经有所发展或是发生改变。
    gui程序本身都有一个mainloop()进行event监听,asyncio再来一个,不知道如何处理了。
    3 条回复    2014-05-13 22:41:18 +08:00
    timonwong
        1
    timonwong  
       2014-05-13 15:52:06 +08:00
    Quick and dirty way:
    GUI loop在main thread上
    I/O loop放到另外一个thread上

    注意io loop中不要直接操作GUI,委托到main thread上操作
    jander
        2
    jander  
    OP
       2014-05-13 17:03:55 +08:00
    在一个thread里放io loop,单独启动一个Server或者Client没问题,
    但是,如果我要在一个thread里放io loop,并启动一个Server,然后在一个Button注册一个事件,开一个线程去调用一个coroutine是不行的,出现错误:
    AssertionError: There is no current event loop in thread 'Thread-3'.

    类似这样:

    ```
    def hello():
    def _x():
    @asyncio.coroutine
    def echo():
    words = 'hello'
    reader, writer = yield from asyncio.open_connection('localhost', 8888)
    writer.write(words.encode('utf-8'))
    answer = yield from reader.readline()
    print(answer.decode('utf-8'))
    writer.close()
    loop = asyncio.new_event_loop()
    loop.run_until_complete(echo())
    loop.close()
    threading.Thread(target=_x).start()
    ```
    jander
        3
    jander  
    OP
       2014-05-13 22:41:18 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2791 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 13:59 · PVG 21:59 · LAX 06:59 · JFK 09:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.