python - 持久子进程.Popen session

标签 python

我正在尝试运行一个命令,然后在同一环境中运行另一个命令(比如说,如果我在第一个命令中设置环境变量,我希望它可用于第二个命令)。我试过这个:

import subprocess

process = subprocess.Popen("echo \"test\"", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);

process.stdin.write("echo \"two\"\n")
process.stdin.flush()

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

但是输出是:

stdout: test

stderr:

我希望它是这样的:

stdout: test
two

stderr:

谁能看出问题所在吗?

最佳答案

问题是您正在写入进程 echostdin,该进程没有从其 stdin 读取,而不是写入类似 bash 的内容会继续读取 stdin。要获得您想要的效果,请查看以下代码:

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

process.stdin.write("echo \"test\"\n")
process.stdin.write("echo \"two\"\n")
process.stdin.flush()

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

输出:

stdout: test
two

stderr: 

更新:看看this question解决流输出问题。

关于python - 持久子进程.Popen session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23140638/

相关文章:

python - 如何断言列表中确实包含预期的元素?

java - 像 Java 一样格式化 Python float

python - 如何在 Pandas 数据框中用中值替换异常值?

python - 如何在 Python 中使用 pprint 进行缩进?

Python如何拥有一个我可以执行并从中导入的模块

python - 使用任意长度索引设置嵌套列表中的元素

python - ValueError:使用套接字和 ssl 模块时 check_hostname 需要 server_hostname

Python 无法获取 iotop 输出

python - 使用 Python 结构模块解压 C 结构

python - Tkinter 文本小部件 : pressing <Return> key goes to line