2024-05-12 22:50:19 发布
网友
我有以下函数,用于在Python中执行系统命令:
def engage_command( command = None ): #os.system(command) return os.popen(command).read()
我使用os模块而不是subprocess模块,因为我处理的是一个与许多环境变量交互的环境
os
subprocess
我如何使用Bash来代替默认的shshell与这种类型的函数一起使用?在
sh
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.
每个os.popen(cmd)调用都会创建一个新的进程来运行cmdshell命令。在
os.popen(cmd)
cmd
或许,从the ^{} documentation that says看不出:
Open a pipe to or from command cmd
“opena pipe”没有清晰的通信:“使用重定向的标准输入或输出启动一个新的shell进程”您可以report a documentation issue。在
如果有任何疑问,source确认每个成功的os.popen()调用都会创建一个新的子进程
os.popen()
the child can't modify its parent process environment (normally)。
考虑:
输出:
==value== ====
====表示第二个命令中的$VAR为空,因为第二个命令与第一个命令在不同的/bin/sh进程中运行。在
====
$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来解决一些问题。在
pexpect
^{} is implemented in terms of ^{} module 。在
每个
os.popen(cmd)
调用都会创建一个新的进程来运行cmd
shell命令。在或许,从the ^{} documentation that says 看不出:
“opena pipe”没有清晰的通信:“使用重定向的标准输入或输出启动一个新的shell进程”您可以report a documentation issue。在
如果有任何疑问,source确认每个成功的
os.popen()
调用都会创建一个新的子进程the child can't modify its parent process environment (normally)。
考虑:
^{pr2}$输出:
====
表示第二个命令中的$VAR
为空,因为第二个命令与第一个命令在不同的/bin/sh
进程中运行。在要在单个进程中运行多个bash命令,请将它们放入脚本中或作为字符串传递:
示例:
输出:
注意:
$VAR
此处不为空。在如果您需要动态生成新命令(基于先前命令的输出),它将创建several issues,并且可以使用
pexpect
模块code example来解决一些问题。在相关问题 更多 >
编程相关推荐