Debian Codegraph @

docs/source/tutorial/tasks-with-trace.py

raw
1 # tasks-with-trace.py
2
3 import trio
4
5
6 async def child1():
7 print(" child1: started! sleeping now...")
8 await trio.sleep(1)
9 print(" child1: exiting!")
10
11
12 async def child2():
13 print(" child2 started! sleeping now...")
14 await trio.sleep(1)
15 print(" child2 exiting!")
16
17
18 async def parent():
19 print("parent: started!")
20 async with trio.open_nursery() as nursery:
21 print("parent: spawning child1...")
22 nursery.start_soon(child1)
23
24 print("parent: spawning child2...")
25 nursery.start_soon(child2)
26
27 print("parent: waiting for children to finish...")
28 # -- we exit the nursery block here --
29 print("parent: all done!")
30
31
32 class Tracer(trio.abc.Instrument):
33 def before_run(self):
34 print("!!! run started")
35
36 def _print_with_task(self, msg, task):
37 # repr(task) is perhaps more useful than task.name in general,
38 # but in context of a tutorial the extra noise is unhelpful.
39 print(f"{msg}: {task.name}")
40
41 def task_spawned(self, task):
42 self._print_with_task("### new task spawned", task)
43
44 def task_scheduled(self, task):
45 self._print_with_task("### task scheduled", task)
46
47 def before_task_step(self, task):
48 self._print_with_task(">>> about to run one step of task", task)
49
50 def after_task_step(self, task):
51 self._print_with_task("<<< task step finished", task)
52
53 def task_exited(self, task):
54 self._print_with_task("### task exited", task)
55
56 def before_io_wait(self, timeout):
57 if timeout:
58 print(f"### waiting for I/O for up to {timeout} seconds")
59 else:
60 print("### doing a quick check for I/O")
61 self._sleep_time = trio.current_time()
62
63 def after_io_wait(self, timeout):
64 duration = trio.current_time() - self._sleep_time
65 print(f"### finished I/O check (took {duration} seconds)")
66
67 def after_run(self):
68 print("!!! run finished")
69
70
71 trio.run(parent, instruments=[Tracer()])