|
1 | 1 | import subprocess |
2 | 2 | from time import sleep |
3 | 3 |
|
4 | | -process = subprocess.Popen("python timer.py 5") |
5 | | - |
6 | | -print(process.poll()) # returns None because process not yet finished |
7 | | -sleep(3) |
8 | | -print(process.poll()) # None |
9 | | -sleep(3) |
10 | | -print(process.poll()) # 0 |
11 | | - |
12 | | -process = subprocess.Popen("python timer.py 5", stdout=subprocess.PIPE) |
13 | | - |
14 | | -print(process.poll()) |
15 | | -print(process.stdout.read()) # reads everything and blocks until EOF |
16 | | -sleep(3) |
17 | | -print(process.poll()) # returns 0 because that is exit code |
18 | | -print(process.stdout.read()) # b'' |
19 | | -sleep(3) |
20 | | -print(process.poll()) # 0 |
21 | | -print(process.stdout.read()) # b'' |
22 | | - |
23 | | - |
24 | | -process = subprocess.Popen("python timer.py 5", stdout=subprocess.PIPE) |
25 | | - |
26 | | -# https://stackoverflow.com/questions/57726771/what-the-difference-between-read-and-read1-in-python |
27 | | -# https://docs.python.org/3/library/io.html?highlight=read1#io.BufferedIOBase.read1 |
28 | | -# https://docs.python.org/3/library/io.html?highlight=read1#io.BufferedIOBase.read |
29 | | - |
30 | | -print(process.poll()) |
31 | | -print(process.stdout.read1()) |
32 | | -sleep(3) |
33 | | -print(process.poll()) |
34 | | -print(process.stdout.read1()) |
35 | | -sleep(3) |
36 | | -print(process.poll()) |
37 | | -print(process.stdout.read1()) |
| 4 | +with subprocess.Popen("python timer.py 5") as process: |
| 5 | + |
| 6 | + print(process.poll()) # returns None because process not yet finished |
| 7 | + sleep(3) |
| 8 | + print(process.poll()) # None |
| 9 | + sleep(3) |
| 10 | + print(process.poll()) # 0 |
| 11 | + |
| 12 | +with subprocess.Popen("python timer.py 5", stdout=subprocess.PIPE) as process: |
| 13 | + |
| 14 | + print(process.poll()) |
| 15 | + print(process.stdout.read()) # reads everything and blocks until EOF |
| 16 | + sleep(3) |
| 17 | + print(process.poll()) # returns 0 because that is exit code |
| 18 | + print(process.stdout.read()) # b'' |
| 19 | + sleep(3) |
| 20 | + print(process.poll()) # 0 |
| 21 | + print(process.stdout.read()) # b'' |
| 22 | + |
| 23 | + |
| 24 | +with subprocess.Popen("python timer.py 5", stdout=subprocess.PIPE) as process: |
| 25 | + |
| 26 | + # https://stackoverflow.com/questions/57726771/what-the-difference-between-read-and-read1-in-python |
| 27 | + # https://docs.python.org/3/library/io.html?highlight=read1#io.BufferedIOBase.read1 |
| 28 | + # https://docs.python.org/3/library/io.html?highlight=read1#io.BufferedIOBase.read |
| 29 | + |
| 30 | + print(process.poll()) |
| 31 | + print(process.stdout.read1()) |
| 32 | + sleep(3) |
| 33 | + print(process.poll()) |
| 34 | + print(process.stdout.read1()) |
| 35 | + sleep(3) |
| 36 | + print(process.poll()) |
| 37 | + print(process.stdout.read1()) |
0 commit comments