@@ -34,10 +34,6 @@ def run(args: Sequence[str], *, log_stdout: bool = False, state: AuditState = Au
3434 the process's `stdout` stream as a string.
3535 """
3636
37- # Run the process with unbuffered I/O, to make the poll-and-read loop below
38- # more responsive.
39- process = Popen (args , bufsize = 0 , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
40-
4137 # NOTE(ww): We frequently run commands inside of ephemeral virtual environments,
4238 # which have long absolute paths on some platforms. These make for confusing
4339 # state updates, so we trim the first argument down to its basename.
@@ -47,22 +43,25 @@ def run(args: Sequence[str], *, log_stdout: bool = False, state: AuditState = Au
4743 stdout = b""
4844 stderr = b""
4945
50- # NOTE: We use `poll()` to control this loop instead of the `read()` call
51- # to prevent deadlocks. Similarly, `read(size)` will return an empty bytes
52- # once `stdout` hits EOF, so we don't have to worry about that blocking.
53- while not terminated :
54- terminated = process .poll () is not None
55- stdout += process .stdout .read () # type: ignore
56- stderr += process .stderr .read () # type: ignore
57- state .update_state (
58- f"Running { pretty_args } " ,
59- stdout .decode (errors = "replace" ) if log_stdout else None ,
60- )
46+ # Run the process with unbuffered I/O, to make the poll-and-read loop below
47+ # more responsive.
48+ with Popen (args , bufsize = 0 , stdout = subprocess .PIPE , stderr = subprocess .PIPE ) as process :
49+ # NOTE: We use `poll()` to control this loop instead of the `read()` call
50+ # to prevent deadlocks. Similarly, `read(size)` will return an empty bytes
51+ # once `stdout` hits EOF, so we don't have to worry about that blocking.
52+ while not terminated :
53+ terminated = process .poll () is not None
54+ stdout += process .stdout .read () # type: ignore
55+ stderr += process .stderr .read () # type: ignore
56+ state .update_state (
57+ f"Running { pretty_args } " ,
58+ stdout .decode (errors = "replace" ) if log_stdout else None ,
59+ )
6160
62- if process .returncode != 0 :
63- raise CalledProcessError (
64- f"{ pretty_args } exited with { process .returncode } " ,
65- stderr = stderr .decode (errors = "replace" ),
66- )
61+ if process .returncode != 0 :
62+ raise CalledProcessError (
63+ f"{ pretty_args } exited with { process .returncode } " ,
64+ stderr = stderr .decode (errors = "replace" ),
65+ )
6766
6867 return stdout .decode ("utf-8" , errors = "replace" )
0 commit comments