Reputation: 3301
I'm developing a command-line application that launches a sub-shell with a pre-generated environment.
subprocess.call(subshell, shell=True, env=custom_environment)
It launches subshell.bat
or subshell.sh
depending on which is the current os.
subshell = "subshell.bat" if os.name == "nt" else "subshell.sh"
But I'm looking to support Cygwin, Git Bash and others running on Windows, and they each need to be given subshell.sh
instead, even though the OS is Windows.
I figured that if there was a way of determining the calling executable of a Python process, I could instead check against that.
if calling_executable in ("bash", "sh"):
subshell = "subshell.sh"
elif calling_executable in ("cmd", "powershell"):
subshell = "subshell.bat"
else:
sys.exit() # unsupported shell
But I'm not sure how to do that. Any ideas or suggestions for how to go about it differently?
Usage example
$ mytool --enter
Entering subshell for bash.exe
ps. this question is phrased exactly the same, but doesn't involve a similar problem, so it didn't feel right to add an unrelated problem to it.
Upvotes: 1
Views: 113
Reputation: 44838
You can use psutil
to do that.
import psutil, os
Parent=psutil.Process(os.getpid()).parent()
ParentName=Parent.name() # e.g. bash, cmd.exe, etc
See that answer for another example. You can get the process' name with psutil.Process(os.getpid()).parent().name()
as well.
Upvotes: 2
Reputation: 461
I would suggest adding command line parameters to indicate the version if you cannot rely on just checking the operating system. It would probably make the program more "Pythonic" because 'explicit is better than implicit'.
Upvotes: 1