推荐学习书目
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 · May 13, 2014 · 4974 views
    This topic created in 4387 days ago, the information mentioned may be changed or developed.
    gui程序本身都有一个mainloop()进行event监听,asyncio再来一个,不知道如何处理了。
    3 replies    2014-05-13 22:41:18 +08:00
    timonwong
        1
    timonwong  
       May 13, 2014
    Quick and dirty way:
    GUI loop在main thread上
    I/O loop放到另外一个thread上

    注意io loop中不要直接操作GUI,委托到main thread上操作
    jander
        2
    jander  
    OP
       May 13, 2014
    在一个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
       May 13, 2014
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1056 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 18:12 · PVG 02:12 · LAX 11:12 · JFK 14:12
    ♥ Do have faith in what you're doing.