怎么可能os.popen公司设置为使用Bash?

2024-05-12 22:50:19 发布

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

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

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

我使用os模块而不是subprocess模块,因为我处理的是一个与许多环境变量交互的环境

我如何使用Bash来代替默认的shshell与这种类型的函数一起使用?在


Tags: 模块函数nonereadreturn环境osdef
1条回答
网友
1楼 · 发布于 2024-05-12 22:50:19
output = subprocess.check_output(command, shell=True, executable='/bin/bash')

^{} is implemented in terms of ^{} module。在


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

  1. 每个os.popen(cmd)调用都会创建一个新的进程来运行cmdshell命令。在

    或许,从the ^{} documentation that says看不出:

    Open a pipe to or from command cmd

    “opena pipe”没有清晰的通信:“使用重定向的标准输入或输出启动一个新的shell进程”您可以report a documentation issue。在

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

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

考虑:

^{pr2}$

输出:

==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,并且可以使用pexpect模块code example来解决一些问题。在

相关问题 更多 >