Skip to content

Commit 2018439

Browse files
committed
Add asynchronous output handling example
1 parent 6b5c364 commit 2018439

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

source-code/subprocess/README.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,8 @@ The exit code can also be retrieved.
88

99
## What is it?
1010

11-
`wc_metrics.py`: this script computes the number of characters, words, and
12-
lines in a file using the shell's `wc` commaand.
11+
1. `wc_metrics.py`: this script computes the number of characters, words, and
12+
lines in a file using the shell's `wc` commaand.
13+
1. `async_handling.py`: this script illustrates how to monitor the standard error
14+
generated by a subprocess.
15+
1. `process.sh`: Bash script to execute by `async_handling.py`.
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/env python
2+
3+
from datetime import datetime
4+
import subprocess
5+
import sys
6+
import time
7+
8+
class Result:
9+
10+
def set(self, value):
11+
self._value = value
12+
13+
@property
14+
def value(self):
15+
return self._value
16+
17+
18+
def execute(cmd, result):
19+
process = subprocess.Popen(cmd,
20+
stdout=subprocess.PIPE,
21+
stderr=subprocess.PIPE,
22+
text=True)
23+
for stderr_line in iter(process.stderr.readline, ''):
24+
yield stderr_line.strip()
25+
stdout, stderr = process.communicate()
26+
return_code = process.wait()
27+
if return_code:
28+
raise subprocess.CalledProcessError(return_code, cmd)
29+
else:
30+
result.set(stdout)
31+
32+
result = Result()
33+
for stderr_line in execute(['bash', 'process.sh'], result):
34+
print(f'{datetime.now()}: {stderr_line}')
35+
print(f'result:\n{result.value}')

source-code/subprocess/process.sh

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env bash
2+
3+
for i in {1..4}
4+
do
5+
(>&2 echo "### info: $i in progress...")
6+
sleep 5
7+
echo "item $i: $((i**2))"
8+
done

0 commit comments

Comments
 (0)