Skip to content

Commit 0f8fa71

Browse files
committed
async std with pipes
1 parent 5de7747 commit 0f8fa71

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

async_std.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'''
2+
Read from a PIPE async.
3+
See https://stackoverflow.com/questions/375427/a-non-blocking-read-on-a-subprocess-pipe-in-python
4+
'''
5+
6+
import subprocess as sp
7+
from threading import Thread
8+
from io import BytesIO
9+
from time import sleep
10+
11+
class Reader(Thread):
12+
def __init__(self, pipe: BytesIO) -> None:
13+
super().__init__()
14+
self.pipe = pipe
15+
self._buffer = BytesIO()
16+
17+
def run(self):
18+
try:
19+
for line in iter(self.pipe.readline, b''):
20+
self._buffer.write(line)
21+
except BrokenPipeError:
22+
return
23+
24+
def get(self):
25+
self.join()
26+
self._buffer.seek(0)
27+
return self._buffer
28+
29+
class PopenAsyncStd(sp.Popen):
30+
def __init__(self, *args, **kw):
31+
super().__init__(
32+
*args,
33+
stdout=sp.PIPE, stderr=sp.PIPE,
34+
**kw,
35+
)
36+
self.outReader = Reader(self.stdout)
37+
self.errReader = Reader(self.stderr)
38+
self.outReader.start()
39+
self.errReader.start()
40+
41+
def reportCollectedOutErr(self):
42+
print(self, 'out:')
43+
print(self.outReader.get().read())
44+
print(self, 'err:')
45+
print(self.errReader.get().read())
46+
47+
def test():
48+
with PopenAsyncStd(['python']) as p:
49+
p.wait()
50+
p.reportCollectedOutErr()
51+
52+
if __name__ == '__main__':
53+
test()

readme.md

+6
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,12 @@ the exception is simply ignored.
151151

152152
[source code](https://github.com/Daniel-Chin/Python_Lib/blob/master/asyncException.py)
153153

154+
## async_std.py
155+
Read from a PIPE async.
156+
See https://stackoverflow.com/questions/375427/a-non-blocking-read-on-a-subprocess-pipe-in-python
157+
158+
[source code](https://github.com/Daniel-Chin/Python_Lib/blob/master/async_std.py)
159+
154160
## audioCues.py
155161
Play audio cues.
156162

0 commit comments

Comments
 (0)