Python: can you tell the name of the calling shell

2019-06-04 04:54发布

问题:

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?

回答1:

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.



回答2:

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

env SHELL_HINT="x$BASH_VERSION" your_script.py

That should evaluate to "x" for zsh and to something else for bash.



回答3:

os.system("echo $0")

This works flawlessly on my system:

cat shell.py: 

    #!/ms/dist/python/PROJ/core/2.5/bin/python

    import os
    print os.system("echo $0")


bash-2.05b$ uname -a
Linux pi929c1n10 2.4.21-32.0.1.EL.msdwhugemem #1 SMP Mon Dec 5 21:32:44 EST 2005 i686 athlon i386 GNU/Linux


pi929c1n10 /ms/user/h/hirscst 8$ ./shell.py
/bin/ksh
pi929c1n10 /ms/user/h/hirscst 9$ bash
bash-2.05b$ ./shell.py
/bin/ksh
bash-2.05b$ 


标签: python shell