I have a python script that is always called from a shell, which can be either zsh or bash.
How can I tell which one called the script?
I have a python script that is always called from a shell, which can be either zsh or bash.
How can I tell which one called the script?
os.system("echo $0")
This works flawlessly on my system:
In Linux you can use procfs:
os.getppid()
returns the PID of parent process. This is portable. But obtaining process name can't be done in portable way. You can parseps
output which is available on all unices, e.g. with psutil.You can't do this in a reliable automated way.
Environment variables can be misleading (a user can maliciously switch them). Most automatic shell variables aren't "leaky", i.e. they are only visible in the shell process, and not for child processes.
You could figure out your parent PID and then search the list of processes for that ID. Doesn't work if you're run in the background (in this case PPID is always 1).
A user could start your program from within a script. Which is the correct shell in this case? The one in which the script was started or the script's shell?
Other programs can use system calls to run your script. In this case, you'd get either their shell or nothing.
If you have absolute control over the user's environment, then put a variable in their profile (check the manuals for BASH and ZSH for a file which is always read at startup. IIRC, it's
.profile
for BASH).[EDIT] Create an alias which is invoked for both shells. In the alias, use
That should evaluate to "x" for zsh and to something else for bash.