我正在使用以下python3.6代码(g.py
)来启动带有自定义提示的交互式bash shell:
import subprocess
import os
envi = os.environ.copy() # env of the python process
envi["PS1"]="my-prompt"
s = subprocess.Popen(['/bin/bash', '-i'], env=envi, shell=False)
s.communicate()
当我在debian伸展9上运行时,我得到:
initial_prompt> ps
PID TTY TIME CMD
1 pts/0 00:00:00 bash
206 pts/0 00:00:00 ps
initial_prompt> python3 g.py
user123§ced47a150f0c:ß$
user123§ced47a150f0c:ß$ ps
PID TTY TIME CMD
1 pts/0 00:00:00 bash
207 pts/0 00:00:00 python3
208 pts/0 00:00:00 bash
209 pts/0 00:00:00 ps
我得到user123§ced47a150f0c:ß$
而不是my-prompt
。
--norc
添加到/bin/bash
时,它可以工作,但我需要阅读~/.bashrc
。~/.bashrc
,PS1
没有改变。我没有~/.bash_profile
文件。PROMPT_COMMAND
env变量为空。默认情况下,bash
没有用于交互式shell的系统范围配置文件。但是,在config-top.h
中有一个编译时选项可以添加一个:
/* System-wide .bashrc file for interactive shells. */
/* #define SYS_BASHRC "/etc/bash.bashrc" */
如果启用了这个(因为我相信它是在Debian中),似乎没有办法在运行时禁用它而不禁用~/.bashrc
。
Debian的/etc/bash.bashrc
用自己的值替换PS1
的任何继承值。当然,您可以在自己的~/.bashrc
中覆盖它,但这意味着在为其他人启动交互式shell时,不能通过环境强制使用PS1
的值。最后,用户可以选择他们的提示,而不是你的提示。
解决方法可能是提供您自己的rcfile,该文件明确地提供用户的~/.bashrc
文件,然后将提示设置为您想要的。在没有临时文件的情况下,我不知道有任何简单的方法:
with NamedTemporaryFile() as tmprc:
print(". ~/.bashrc", file=tmprc)
print('PS1="my-prompt "', file=tmprc)
s = subprocess.Popen(['/bin/bash', '-i', '--rcfile', tmprc.name])
在Debian Stretch下,PS1
设置在/etc/bash.bashrc
:
# set a fancy prompt (non-color, overwrite the one in /etc/profile)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
这也是由/etc/profile
采购的:
if [ "${PS1-}" ]; then
if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
# The file bash.bashrc already sets the default PS1.
# PS1='\h:\w\$ '
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
else
if [ "`id -u`" -eq 0 ]; then
PS1='# '
else
PS1='$ '
fi
fi
fi