Skip to content

Commit 9f1fb76

Browse files
committed
einfaches Beispiel für asyncio
1 parent 4eb311b commit 9f1fb76

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Level_8/async.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env python3
2+
import asyncio
3+
import string
4+
from sys import argv
5+
6+
# alternativ (ab Python 3.5): async def
7+
@asyncio.coroutine
8+
def print_string(mystring, wait=0.1):
9+
while True:
10+
print(mystring, end="", flush=True)
11+
yield from asyncio.sleep(wait) # alternativ (ab Python 3.5): await
12+
13+
"""
14+
Die Event-Loop ist bei asyncio sehr wichtig.
15+
Sie kontrolliert die Ausführung innerhalb des aktuellen (und meistens einzigen) Threads.
16+
"""
17+
loop = asyncio.get_event_loop()
18+
19+
if len(argv) > 1:
20+
count = int(argv[1])
21+
else:
22+
count = 2
23+
24+
for letter in string.ascii_uppercase[0:count]:
25+
# create_task erstellt einen Task aus einer Coroutine und führt ihn aus.
26+
loop.create_task(print_string(letter))
27+
28+
try:
29+
# Übergibt die Kontrolle des Ablaufs an die Loop.
30+
loop.run_forever()
31+
except KeyboardInterrupt: # bei Drücken von Strg+C
32+
loop.stop() # beende die Loop
33+
loop.close() # schließe die Loop
34+
35+
# siehe auch: https://docs.python.org/3.6/library/asyncio.html

0 commit comments

Comments
 (0)