I have a python application that has a shell that needs to do some setup based on whether the shell it's running in is the Windows Command Prompt (cmd) or Powershell.
I haven't been able to figure out how to detect if the application is running in powershell or cmd.
From my searches on stackoverflow and Google, it seems the only way to do this is to use psutil to find the name of the parent process.
Is there a nicer way?
psutilis your best option. Your Python script is run by the Python interpreter regardless of whether it was launched from a PowerShell or CMD process.os.systemuses cmd.exe. Thesubprocessmodule uses WinAPICreateProcess, which creates a process using a PE executable (i.e. .EXE, but the extension doesn't matter) or starts cmd.exe when passed the path to a .BAT or .CMD file. Theshell=Trueoption of subprocess uses the%ComSpec%shell, which is usually cmd.exe.psutilpackage in their question edits. Instead, see this genuinely useful answer to a similar question elsewhere. tl;dr:is_powershell = bool(re.fullmatch('pwsh|pwsh.exe|powershell.exe', psutil.Process(os.getppid()).name())).