Detect whether current shell is powershell in pyth

2020-02-12 11:08发布

问题:

What's the recommended way to check which shell is my python program running inside? I know I can query os.environ.get('SHELL') for the shell name, but what can I use to determine powershell?

回答1:

Generally, environment variable SHELL does not tell you what shell invoked your script, it only tells you the binary path of the current user's default shell (on Unix-like platforms), as chepner notes.

To detect what shell invoked your script, you must examine the script's parent process.

The following works with the psutil package installed (it is both v2- and v3-compatible):

import os, psutil, re

# Get the parent process name.
pprocName = psutil.Process(os.getppid()).name()

# See if it is Windows PowerShell (powershell.exe) or PowerShell Core (pwsh[.exe]):
isPowerShell = bool(re.fullmatch('pwsh|pwsh.exe|powershell.exe', pprocName))

If installing a package is not an option, you can use the following workaround to detect PowerShell specifically, but note the constraints:

  • It presumes a standard PowerShell installation, specifically with respect to environment variable PSModulePath: that is, PSModulePath must either:

    • not be predefined at all outside of PowerShell (Unix-like platforms)
    • or must have just one or two entries outside of PowerShell (Windows, predefined via the registry)[1].
  • It presumes that the script wasn't invoked via nested shell invocations; specifically, if you launched a different shell from PowerShell, which then launched your script, the solution below would still indicate that your script was launched by PowerShell.

import os

isPowerShell = len(os.getenv('PSModulePath', '').split(os.pathsep)) >= 3 

Note that when PowerShell starts up it ensures that at least 3 locations are present in PSModulePath, on all platforms (the in-box/system-modules location, the all-users location, and the current-user location). As stated, outside of PowerShell the variable isn't predefined at all on Unix, and on Windows it is predefined with at most 2 locations.


[1] Older Windows 10 versions predefined just the system-modules location, $env:SystemRoot\System32\WindowsPowerShell\v1.0\Modules, whereas more recent versions additionally predefine the all-users location, $env:ProgramFiles\WindowsPowerShell\Modules.