Navigation Menu

Skip to content
This repository has been archived by the owner on May 31, 2021. It is now read-only.

Commit

Permalink
Twisted example
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Jul 22, 2016
1 parent e2b759e commit e7c0de2
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.rst
Expand Up @@ -49,3 +49,4 @@ See also

* https://github.com/python/asyncio
* http://krondo.com/an-introduction-to-asynchronous-programming-and-twisted/
* http://curio.readthedocs.io/en/latest/tutorial.html
19 changes: 19 additions & 0 deletions examples/asyncio_deferred.py
@@ -0,0 +1,19 @@
import asyncio


async def multiply(x):
result = x * 2
await asyncio.sleep(1)
return result


async def steps(x):
result = await multiply(x)
print("result: %s" % result)


loop = asyncio.get_event_loop()
coro = steps(5)
loop.run_until_complete(coro)
loop.close()

28 changes: 28 additions & 0 deletions examples/twisted_deferred.py
@@ -0,0 +1,28 @@
from twisted.internet import defer
from twisted.internet import reactor


def multiply(x):
result = x * 2
d = defer.Deferred()
reactor.callLater(1.0, d.callback, result)
return d


def step1(x):
return multiply(x)


def step2(result):
print("result: %s" % result)

reactor.stop()


d = defer.Deferred()
d.addCallback(step1)
d.addCallback(step2)
d.callback(5)

reactor.run()

4 changes: 2 additions & 2 deletions getting_help.rst
Expand Up @@ -24,5 +24,5 @@ read new questions but also read answers of previous questions.
IRC
===

There is an IRC channel ``#asyncio`` on the Freenode server.

There is an IRC channel ``#asyncio`` on the `Freenode server
<https://freenode.net/>`_.
15 changes: 14 additions & 1 deletion twisted.rst
Expand Up @@ -13,6 +13,19 @@ Twisted asyncio
======================== ==================================
Deferred asyncio.Future
deferToThread(func) loop.run_in_executor(None, func)
@inlineCallbacks @coroutine
@inlineCallbacks async def
reactor.run() loop.run_forever()
======================== ==================================


Deferred example
================

+--------------------------------------------------+--------------------------------------------------+
| Twisted | asyncio |
+==================================================+==================================================+
| Basic Twisted example using deferred: | Similar example written using asyncio: |
| | |
| .. literalinclude:: examples/twisted_deferred.py | .. literalinclude:: examples/asyncio_deferred.py |
+--------------------------------------------------+--------------------------------------------------+

0 comments on commit e7c0de2

Please sign in to comment.