从 subprocess.Popen 获取多个命令的输出 [英] Get the output of multiple commands from subprocess.Popen

查看:76
本文介绍了从 subprocess.Popen 获取多个命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行一个命令,获取它的输出,然后在同一环境中运行另一个命令(假设我在第一个命令中设置了一个环境变量,我希望它可用于第二个命令).我试过这个:

I am trying to run a command, get it's output, then later run another command in the same environment (say if I set an environment variable in the first command, I want it to be available to the second command). I tried this:

import subprocess

process = subprocess.Popen("/bin/bash", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);

process.stdin.write("export MyVar=\"Test\"\n")
process.stdin.write("echo $MyVar\n")
process.stdin.flush()

stdout, stderr  = process.communicate()
print "stdout: " + str(stdout)

# Do it again
process.stdin.write("echo $MyVar\n")
process.stdin.flush()

stdout, stderr = process.communicate()
print "stdout: " + str(stdout)

但是communication() 一直读到最后,所以这不是一个有效的技术.(我明白了:)

but communicate() reads until the end, so this is not a valid technique. (I get this:)

stdout: Test

Traceback (most recent call last):
  File "./MultipleCommands.py", line 15, in <module>
    process.stdin.write("echo $MyVar\n")
ValueError: I/O operation on closed file

我见过这个:https://stackoverflow.com/a/15654218/284529,但它没有t 给出一个如何做它建议的工作示例.任何人都可以演示如何做到这一点?我还看到了其他涉及在循环中不断检查输出的技术,但这不符合获取命令的输出"的心态 - 它只是将其视为流.

I have seen this: https://stackoverflow.com/a/15654218/284529 , but it doesn't give a working example of how to do what it proposes. Can anyone demonstrate how to do this? I have also seen other techniques that involve constantly checking for output in a loop, but this doesn't fit the "get the output of a command" mentality - it is just treating it like a stream.

推荐答案

要获得多个命令的输出,只需将它们组合成一个脚本即可:

To get the output of multiple commands, just combine them into a single script:

#!/usr/bin/env python
import subprocess
import sys

output = subprocess.check_output("""
export MyVar="Test"
echo $MyVar
echo ${MyVar/est/ick}
""", shell=True, executable='/bin/bash', universal_newlines=True)
sys.stdout.write(output)

输出

Test
Tick

这篇关于从 subprocess.Popen 获取多个命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆