-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtail.py
56 lines (44 loc) · 1.44 KB
/
tail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import asyncio
import aiofiles
import functools
import sys
FILE_READ_INTERVAL = 1.0
async def get_pipe_reader(stream):
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(loop=loop)
await loop.connect_read_pipe(functools.partial(asyncio.StreamReaderProtocol, reader), stream)
return reader
async def main():
async def echo_stdin():
stdin_reader = await get_pipe_reader(sys.stdin)
while True:
print((await stdin_reader.readline()).decode("utf-8"))
async def counter():
c = 0
while True:
c += 1
print(c)
await asyncio.sleep(1)
async def echo_file_sync():
with open("syncin.txt", "w+b") as f:
while True:
line = f.readline()
if line:
print(line.decode("utf-8"))
else:
await asyncio.sleep(FILE_READ_INTERVAL)
async def echo_file():
async with aiofiles.open("asyncin.txt", "w+b") as f:
while True:
line = await f.readline()
if line:
print(line.decode("utf-8"))
else:
await asyncio.sleep(FILE_READ_INTERVAL)
await asyncio.gather(
asyncio.create_task(counter()),
asyncio.create_task(echo_stdin()),
asyncio.create_task(echo_file()),
asyncio.create_task(echo_file_sync()),
)
asyncio.run(main())