| 1 |
"""Windows-specific implementation of process utilities. |
| 2 |
|
| 3 |
This file is only meant to be imported by process.py, not by end-users. |
| 4 |
""" |
| 5 |
|
| 6 |
import ctypes |
| 7 |
import os |
| 8 |
import subprocess |
| 9 |
import sys |
| 10 |
import time |
| 11 |
from ctypes import POINTER, c_int |
| 12 |
from ctypes.wintypes import HLOCAL, LPCWSTR |
| 13 |
from subprocess import STDOUT |
| 14 |
from threading import Thread |
| 15 |
from types import TracebackType |
| 16 |
from typing import List, Optional |
| 17 |
|
| 18 |
from . import py3compat |
| 19 |
from ._process_common import arg_split as py_arg_split |
| 20 |
|
| 21 |
from ._process_common import process_handler, read_no_interrupt |
| 22 |
from .encoding import DEFAULT_ENCODING |
| 23 |
|
| 24 |
|
| 25 |
class AvoidUNCPath: |
| 26 |
"""A context manager to protect command execution from UNC paths. |
| 27 |
|
| 28 |
In the Win32 API, commands can't be invoked with the cwd being a UNC path. |
| 29 |
This context manager temporarily changes directory to the 'C:' drive on |
| 30 |
entering, and restores the original working directory on exit. |
| 31 |
|
| 32 |
The context manager returns the starting working directory *if* it made a |
| 33 |
change and None otherwise, so that users can apply the necessary adjustment |
| 34 |
to their system calls in the event of a change. |
| 35 |
|
| 36 |
Examples |
| 37 |
-------- |
| 38 |
:: |
| 39 |
cmd = 'dir' |
| 40 |
with AvoidUNCPath() as path: |
| 41 |
if path is not None: |
| 42 |
cmd = '"pushd %s &&"%s' % (path, cmd) |
| 43 |
os.system(cmd) |
| 44 |
""" |
| 45 |
|
| 46 |
def __enter__(self) -> Optional[str]: |
| 47 |
self.path = os.getcwd() |
| 48 |
self.is_unc_path = self.path.startswith(r"\\") |
| 49 |
if self.is_unc_path: |
| 50 |
# change to c drive (as cmd.exe cannot handle UNC addresses) |
| 51 |
os.chdir("C:") |
| 52 |
return self.path |
| 53 |
else: |
| 54 |
# We return None to signal that there was no change in the working |
| 55 |
# directory |
| 56 |
return None |
| 57 |
|
| 58 |
def __exit__( |
| 59 |
self, |
| 60 |
exc_type: Optional[type[BaseException]], |
| 61 |
exc_value: Optional[BaseException], |
| 62 |
traceback: Optional[TracebackType], |
| 63 |
) -> None: |
| 64 |
if self.is_unc_path: |
| 65 |
os.chdir(self.path) |
| 66 |
|
| 67 |
|
| 68 |
def _system_body(p: subprocess.Popen[bytes]) -> int: |
| 69 |
"""Callback for _system.""" |
| 70 |
enc = DEFAULT_ENCODING |
| 71 |
|
| 72 |
# Dec 2024: in both of these functions, I'm not sure why we .splitlines() |
| 73 |
# the bytes and then decode each line individually instead of just decoding |
| 74 |
# the whole thing at once. |
| 75 |
def stdout_read() -> None: |
| 76 |
try: |
| 77 |
assert p.stdout is not None |
| 78 |
for byte_line in (read_no_interrupt(p.stdout) or b"").splitlines(): |
| 79 |
line = byte_line.decode(enc, "replace") |
| 80 |
print(line, file=sys.stdout) |
| 81 |
except Exception as e: |
| 82 |
print(f"Error reading stdout: {e}", file=sys.stderr) |
| 83 |
|
| 84 |
def stderr_read() -> None: |
| 85 |
try: |
| 86 |
assert p.stderr is not None |
| 87 |
for byte_line in (read_no_interrupt(p.stderr) or b"").splitlines(): |
| 88 |
line = byte_line.decode(enc, "replace") |
| 89 |
print(line, file=sys.stderr) |
| 90 |
except Exception as e: |
| 91 |
print(f"Error reading stderr: {e}", file=sys.stderr) |
| 92 |
|
| 93 |
stdout_thread = Thread(target=stdout_read) |
| 94 |
stderr_thread = Thread(target=stderr_read) |
| 95 |
|
| 96 |
stdout_thread.start() |
| 97 |
stderr_thread.start() |
| 98 |
|
| 99 |
# Wait to finish for returncode. Unfortunately, Python has a bug where |
| 100 |
# wait() isn't interruptible (https://bugs.python.org/issue28168) so poll in |
| 101 |
# a loop instead of just doing `return p.wait()` |
| 102 |
while True: |
| 103 |
result = p.poll() |
| 104 |
if result is None: |
| 105 |
time.sleep(0.01) |
| 106 |
else: |
| 107 |
break |
| 108 |
|
| 109 |
# Join the threads to ensure they complete before returning |
| 110 |
stdout_thread.join() |
| 111 |
stderr_thread.join() |
| 112 |
|
| 113 |
return result |
| 114 |
|
| 115 |
|
| 116 |
def system(cmd: str) -> Optional[int]: |
| 117 |
"""Win32 version of os.system() that works with network shares. |
| 118 |
|
| 119 |
Note that this implementation returns None, as meant for use in IPython. |
| 120 |
|
| 121 |
Parameters |
| 122 |
---------- |
| 123 |
cmd : str or list |
| 124 |
A command to be executed in the system shell. |
| 125 |
|
| 126 |
Returns |
| 127 |
------- |
| 128 |
int : child process' exit code. |
| 129 |
""" |
| 130 |
# The controller provides interactivity with both |
| 131 |
# stdin and stdout |
| 132 |
# import _process_win32_controller |
| 133 |
# _process_win32_controller.system(cmd) |
| 134 |
|
| 135 |
with AvoidUNCPath() as path: |
| 136 |
if path is not None: |
| 137 |
cmd = '"pushd %s &&"%s' % (path, cmd) |
| 138 |
res = process_handler(cmd, _system_body) |
| 139 |
return res |
| 140 |
|
| 141 |
|
| 142 |
def getoutput(cmd: str) -> str: |
| 143 |
"""Return standard output of executing cmd in a shell. |
| 144 |
|
| 145 |
Accepts the same arguments as os.system(). |
| 146 |
|
| 147 |
Parameters |
| 148 |
---------- |
| 149 |
cmd : str or list |
| 150 |
A command to be executed in the system shell. |
| 151 |
|
| 152 |
Returns |
| 153 |
------- |
| 154 |
stdout : str |
| 155 |
""" |
| 156 |
|
| 157 |
with AvoidUNCPath() as path: |
| 158 |
if path is not None: |
| 159 |
cmd = '"pushd %s &&"%s' % (path, cmd) |
| 160 |
out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT) |
| 161 |
|
| 162 |
if out is None: |
| 163 |
out = b"" |
| 164 |
return py3compat.decode(out) |
| 165 |
|
| 166 |
|
| 167 |
try: |
| 168 |
windll = ctypes.windll # type: ignore [attr-defined] |
| 169 |
CommandLineToArgvW = windll.shell32.CommandLineToArgvW |
| 170 |
CommandLineToArgvW.arg_types = [LPCWSTR, POINTER(c_int)] |
| 171 |
CommandLineToArgvW.restype = POINTER(LPCWSTR) |
| 172 |
LocalFree = windll.kernel32.LocalFree |
| 173 |
LocalFree.res_type = HLOCAL |
| 174 |
LocalFree.arg_types = [HLOCAL] |
| 175 |
|
| 176 |
def arg_split( |
| 177 |
commandline: str, posix: bool = False, strict: bool = True |
| 178 |
) -> List[str]: |
| 179 |
"""Split a command line's arguments in a shell-like manner. |
| 180 |
|
| 181 |
This is a special version for windows that use a ctypes call to CommandLineToArgvW |
| 182 |
to do the argv splitting. The posix parameter is ignored. |
| 183 |
|
| 184 |
If strict=False, process_common.arg_split(...strict=False) is used instead. |
| 185 |
""" |
| 186 |
# CommandLineToArgvW returns path to executable if called with empty string. |
| 187 |
if commandline.strip() == "": |
| 188 |
return [] |
| 189 |
if not strict: |
| 190 |
# not really a cl-arg, fallback on _process_common |
| 191 |
return py_arg_split(commandline, posix=posix, strict=strict) |
| 192 |
argvn = c_int() |
| 193 |
result_pointer = CommandLineToArgvW(commandline.lstrip(), ctypes.byref(argvn)) |
| 194 |
try: |
| 195 |
result_array_type = LPCWSTR * argvn.value |
| 196 |
result = [ |
| 197 |
arg |
| 198 |
for arg in result_array_type.from_address( |
| 199 |
ctypes.addressof(result_pointer.contents) |
| 200 |
) |
| 201 |
if arg is not None |
| 202 |
] |
| 203 |
finally: |
| 204 |
# for side effects |
| 205 |
_ = LocalFree(result_pointer) |
| 206 |
return result |
| 207 |
except AttributeError: |
| 208 |
arg_split = py_arg_split |
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
def check_pid(pid: int) -> bool: |
| 213 |
# OpenProcess returns 0 if no such process (of ours) exists |
| 214 |
# positive int otherwise |
| 215 |
return bool(windll.kernel32.OpenProcess(1, 0, pid)) |