refactor: remove psutil dependency and check parent process only on Windows

This commit is contained in:
Paul Gauthier (aider) 2024-09-10 09:30:36 -07:00
parent e5ff5eff75
commit 625a49752b

View file

@ -25,17 +25,14 @@ def run_cmd(command, verbose=False, error_print=None):
def get_windows_parent_process_name(): def get_windows_parent_process_name():
try: try:
if platform.system() == "Windows": kernel32 = ctypes.windll.kernel32
kernel32 = ctypes.windll.kernel32 h_process = kernel32.OpenProcess(0x0400, False, os.getppid())
h_process = kernel32.OpenProcess(0x0400, False, os.getppid()) exe_path = ctypes.create_unicode_buffer(260)
exe_path = ctypes.create_unicode_buffer(260) kernel32.QueryFullProcessImageNameW(
kernel32.QueryFullProcessImageNameW( h_process, 0, exe_path, ctypes.byref(ctypes.c_ulong(260))
h_process, 0, exe_path, ctypes.byref(ctypes.c_ulong(260)) )
) kernel32.CloseHandle(h_process)
kernel32.CloseHandle(h_process) return os.path.basename(exe_path.value).lower()
return os.path.basename(exe_path.value).lower()
else:
return psutil.Process(os.getppid()).name().lower()
except Exception: except Exception:
return None return None
@ -46,20 +43,20 @@ def run_cmd_subprocess(command, verbose=False):
try: try:
shell = os.environ.get("SHELL", "/bin/sh") shell = os.environ.get("SHELL", "/bin/sh")
parent_process = get_parent_process_name() parent_process = None
# Determine the appropriate shell # Determine the appropriate shell
if platform.system() == "Windows": if platform.system() == "Windows":
parent_process = get_windows_parent_process_name()
if parent_process == "powershell.exe": if parent_process == "powershell.exe":
command = f"powershell -Command {command}" command = f"powershell -Command {command}"
else: # else: Assume cmd.exe or other Windows shell, use the command as-is
# Assume cmd.exe or other Windows shell
pass # Use the command as-is
if verbose: if verbose:
print("Running command:", command) print("Running command:", command)
print("SHELL:", shell) print("SHELL:", shell)
print("Parent process:", parent_process) if platform.system() == "Windows":
print("Parent process:", parent_process)
process = subprocess.Popen( process = subprocess.Popen(
command, command,