从python生成bash并打印消息

2024-05-16 00:14:01 发布

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

我想知道是否有办法生成一个登录shell并向用户显示一条消息。规则:

  • 用户有自己的~/.bashrc,我们不想覆盖它
  • 避免使用到子流程的管道

我正在做的是:

def do_bash(tokens, state):
    """
    Drop into system shell or execute shell commands. Examples:

    - bash
    - bash -c "ls ~/.* | grep shell"
    """
    cmd = ["bash", "-l"]
    if len(tokens):
        cmd.extend(tokens)
    subprocess.call(cmd)

我曾尝试将-l-c echo "<message>"组合,但这只会在新的shell中显示消息,然后返回

UDPATE:为了简化这一点,我想执行subprocess.call(["bash", "-l", "<magic I am not sure of>"]),从用户的角度来看:

$ python ./mycode.py
I0000 03:16:11 [mycode] Various logging messages until subprocess is called

  You have dropped into a temporary shell but you are still
  within "mycode.py" program. You can use "exit" to continue
  running the script. This shell allows to you to do foo and bar.

bash$

Tags: to用户pycmdbashyou消息shell
2条回答

只需bash就可以从/etc/bashrc+~/.bashrc获得带有加载环境的交互式shell

如果您想要一个登录shell,bash -l是正确的

为了显示您的借口(使用bash),您需要再次调用bash,因为它既可以运行以执行给定的命令,也可以作为交互式shell。如果您真的不需要bash解析这个借口,我建议改为使用python输出这个借口

如果使用-l调用bash,则不会执行~/.bashrc。相反,因为您请求一个登录shell,所以执行~/.bash_profile(如果存在)

因此,我在我的~/.bash_profile中提到:

source ~/.bashrc

您可能希望在不使用-l的情况下调用bash

相关问题 更多 >