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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- How to get the return code of a shell script in lu
- Evil ctypes hack in python
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):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: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.
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
.