How to obtain the name of the calling shell in Python?

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?

Answer

In Linux you can use procfs:

>>> os.readlink('/proc/%d/exe' % os.getppid())
'/bin/bash'

os.getppid() returns the PID of parent process. This is portable. But obtaining process name can’t be done in portable way. You can parse ps output which is available on all unices, e.g. with psutil.

Leave a Reply

Your email address will not be published. Required fields are marked *