os.popen如何设置为使用Bash?

How can os.popen be set to use Bash?

我有以下函数用于在Python中执行系统命令:

def engage_command(
    command = None
    ):
    #os.system(command)
    return os.popen(command).read()

我正在使用 os 模块而不是 subprocess 模块,因为我处理的是一个单一的环境,我在其中与许多环境变量等进行交互。

如何将 Bash 与这种类型的函数一起使用而不是默认的 sh shell?

output = subprocess.check_output(command, shell=True, executable='/bin/bash')

os.popen() is implemented in terms of subprocess module.


I am dealing with a single environment in which I am interacting with many environment variables etc.

  1. 每个 os.popen(cmd) 调用都会创建一个 new /bin/sh 进程,以 运行 cmd shell 命令。

    也许,从the os.popen() documentation that says看不明显:

    Open a pipe to or from command cmd

    "open a pipe" 沟通不清晰:"start a new shell process with a redirected standard input or output" -- 你可以 report a documentation issue.

    如有疑问; source 确认每个成功的 os.popen() 调用都会创建一个新的子进程

  2. the child can't modify its parent process environment (normally).

考虑:

import os
#XXX BROKEN: it won't work as you expect
print(os.popen("export VAR=value; echo ==$VAR==").read())
print(os.popen("echo ==$VAR==").read())

输出:

==value==

====

==== 表示 $VAR 在第二个命令中为空,因为第二个命令 运行 与第一个命令处于不同的 /bin/sh 进程中。

要运行单个进程中的几个bash命令,将它们放在脚本中或作为字符串传递:

output = check_output("\n".join(commands), shell=True, executable='/bin/bash')

示例:

#!/usr/bin/env python
from subprocess import check_output

output = check_output("""
    export VAR=value; echo ==$VAR==
    echo ==$VAR==
    """, shell=True, executable='/bin/bash')
print(output.decode())

输出:

==value==
==value==

注意:$VAR此处不为空

如果您需要动态生成新命令(基于先前命令的输出);它创建 several issues and some of the issues could be fixed using pexpect module: code example.