/bin/bash i覆盖PS1

2024-05-13 11:55:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下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 stretch 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_COMMANDenv变量为空。你知道吗
  • 在MacOS上,它就像一个魔咒。你知道吗

Tags: pyimportenvbashosmyshellprompt
2条回答

默认情况下,bash没有交互式shell的系统范围配置文件。但是,在config-top.h中有一个编译时选项可以添加一个:

/* System-wide .bashrc file for interactive shells. */
/* #define SYS_BASHRC "/etc/bash.bashrc" */

如果启用了这个功能(我相信在Debian中是这样),那么在运行时如果不禁用~/.bashrc,似乎就无法禁用它。你知道吗

Debian的/etc/bash.bashrcPS1的任何继承值替换为它自己的值。当然,您可以在自己的~/.bashrc中重写它,但这意味着您不能在为其他人启动交互式shell时通过环境强制值PS1。最后,由用户选择他们的提示是什么,而不是你的。你知道吗

一种解决方法可能是提供自己的rcfile,它显式地获取用户的~/.bashrc文件,然后将提示设置为所需的内容。我不知道有什么简单的方法可以在没有临时文件的情况下做到这一点:

with NamedTemporaryFile(mode='w+', buffering=True, delete=False) as tmprc:
    tmprc.write('. ~/.bashrc\n')
    tmprc.write('PS1="my-prompt "\n')

    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

相关问题 更多 >