|
2 | 2 | # SPDX-License-Identifier: MIT |
3 | 3 |
|
4 | 4 | from contextlib import contextmanager |
| 5 | +import errno |
5 | 6 | import os |
6 | 7 | import platform |
7 | 8 | import select |
|
10 | 11 | import tempfile |
11 | 12 | from typing import Union |
12 | 13 |
|
| 14 | +if sys.platform != 'win32': |
| 15 | + import fcntl |
| 16 | + |
13 | 17 | # Type for arguments that accept file paths |
14 | 18 | PathLike = Union[str, bytes, os.PathLike] |
15 | 19 |
|
@@ -91,18 +95,39 @@ def run(args): |
91 | 95 | Based on https://stackoverflow.com/a/12272262 and |
92 | 96 | https://stackoverflow.com/a/7730201 |
93 | 97 | """ |
94 | | - p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
95 | | - universal_newlines=True) |
| 98 | + # Windows doesn't support select.select and fcntl module so just default to |
| 99 | + # using subprocess.run. In this case, show_stdout/show_stderr won't work. |
| 100 | + if sys.platform == 'win32': |
| 101 | + subprocess.run(args) |
| 102 | + return |
| 103 | + |
| 104 | + # Helper function to add the O_NONBLOCK flag to a file descriptor |
| 105 | + def make_async(fd): |
| 106 | + fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK) |
| 107 | + |
| 108 | + # Helper function to read some data from a file descriptor, ignoring EAGAIN errors |
| 109 | + def read_async(fd): |
| 110 | + try: |
| 111 | + return fd.read() |
| 112 | + except IOError as e: |
| 113 | + if e.errno != errno.EAGAIN: |
| 114 | + raise e |
| 115 | + else: |
| 116 | + return '' |
| 117 | + |
| 118 | + p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 119 | + make_async(p.stdout) |
| 120 | + make_async(p.stderr) |
96 | 121 |
|
97 | 122 | while True: |
98 | | - select.select([p.stdout, p.stderr], [], []) |
| 123 | + select.select([p.stdout, p.stderr], [], [], 0) |
99 | 124 |
|
100 | | - stdout_data = p.stdout.read() |
101 | | - stderr_data = p.stderr.read() |
| 125 | + stdout_data = read_async(p.stdout) |
| 126 | + stderr_data = read_async(p.stderr) |
102 | 127 | if stdout_data: |
103 | | - sys.stdout.write(stdout_data) |
| 128 | + sys.stdout.write(stdout_data.decode()) |
104 | 129 | if stderr_data: |
105 | | - sys.stderr.write(stderr_data) |
| 130 | + sys.stderr.write(stderr_data.decode()) |
106 | 131 |
|
107 | 132 | if p.poll() is not None: |
108 | 133 | break |
0 commit comments