I want to obtain the (zsh) shell prompt in a python script. Simply using
import os
prompt = os.environ['PS1']
seems not to be the right way, because PS1
is usually not forwarded to subprocesses. In the same manner env | grep PS
in a shell fails.
So I concluded that I should probably start an interactive shell as subprocess and querry its prompt. From a shell I can just do
zsh -c -i 'echo $PS1'
(must be single quotes, double quotes fail)
I tried to do the same from python(2.7) with subprocess
like this:
print subprocess.check_output(['-i','-c',r"'echo $PS1'"],executable="/bin/zsh")
This fails with
subprocess.CalledProcessError: Command '['-i', '-c', "'echo $PS1'"]' returned non-zero exit status 127
I think this is not because of the $PS1
but due to the way how i provide the echo-part as argument, because also echoing bare strings in this way fails.
Trying back and forth various combinations I ended up with
prompt = subprocess.check_output("""zsh -c -i 'echo $PS1'""",shell=True,executable="/bin/zsh")
which seems to do the job but seems wrong to me as this is starting a shell and in that shell calling yet another shell with -c -i 'echo $PS1'
.
What's the correct way of obtaining the shell prompt.
executable
does not, what you think it does. It is used to replace the executable from the given command line. Withshell=False
it will replace the first element of the argument list, withshell=True
it will be used as the shell instead ofsh
. It is not usually needed. See here for more information.