Last active
November 24, 2018 04:48
-
-
Save objarni/48f0f4e99c1c44993a2173922e0c914d to your computer and use it in GitHub Desktop.
trio learning
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# License - MIT / do whatever | |
## rev3 - add result gathering | |
async def child(name, journal): | |
print(f"{name}: My name is: " + name) | |
staytime = random.randint(1, 3) | |
print(f"{name}: I will stay for {staytime} seconds.") | |
print(f"{name}: I will jot down my name in the journal") | |
journal.append(name) | |
await trio.sleep(staytime) | |
print(f"{name}: Leaving nursery.") | |
async def run(): | |
print("Opening nursery.") | |
results = [] | |
async with trio.open_nursery() as nursery: | |
print("Nursery open.") | |
nursery.start_soon(child, 'olof', results) | |
nursery.start_soon(child, 'gustav', results) | |
print("All children have been welcomed.") | |
print("Nursery closed - children left.") | |
print(f"Result is: {results}") | |
if __name__ == '__main__': | |
trio.run(run) | |
## rev2 - add nicer output, random sleep | |
async def child(name): | |
print(f"{name}: My name is: " + name) | |
staytime = random.randint(1, 4) | |
print(f"{name}: I will stay for {staytime} seconds.") | |
await trio.sleep(staytime) | |
print(f"{name}: Leaving nursery.") | |
async def run(): | |
print("Opening nursery.") | |
async with trio.open_nursery() as nursery: | |
print("Nursery open.") | |
nursery.start_soon(child, 'olof') | |
nursery.start_soon(child, 'gustav') | |
print("All children have been welcomed.") | |
print("Nursery closed - children left.") | |
if __name__ == '__main__': | |
trio.run(run) | |
## rev1 - working version with await | |
from __future__ import print_function | |
import trio | |
async def child(name): | |
print("My name is: " + name) | |
await trio.sleep(1) | |
async def run(): | |
print("Opening nursery.") | |
async with trio.open_nursery() as nursery: | |
print("Nursery open.") | |
nursery.start_soon(child, 'olof') | |
nursery.start_soon(child, 'gustav') | |
print("All children have been welcomed.") | |
print("Nursery closed - children left.") | |
if __name__ == '__main__': | |
trio.run(run) | |
## rev0 - program skeleton but forgot await | |
from __future__ import print_function | |
import trio | |
def child(name): | |
print("My name is: " + name) | |
trio.sleep(1) | |
def run(): | |
print("Opening nursery.") | |
with trio.open_nursery() as nursery: | |
print("Nursery open.") | |
nursery.start_soon(child, 'olof') | |
nursery.start_soon(child, 'gustav') | |
print("All children have been welcomed.") | |
print("Nursery closed - children left.") | |
if __name__ == '__main__': | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment