/ bin / bash -i覆盖PS1

问题描述 投票:0回答:2

我正在使用以下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
  • ~/.bashrcPS1没有改变。我没有~/.bash_profile文件。
  • PROMPT_COMMAND env变量为空。
  • 在MacOS上,它就像一个魅力。
python python-3.x bash shell subprocess
2个回答
1
投票

默认情况下,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])

0
投票

在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
© www.soinside.com 2019 - 2024. All rights reserved.