Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用任意变量保存subprocess.Popen的输出_Python - Fatal编程技术网

Python 使用任意变量保存subprocess.Popen的输出

Python 使用任意变量保存subprocess.Popen的输出,python,Python,我想从shell命令中检索输出 In [7]: subprocess.Popen("yum list installed", shell=True) Out[7]: <subprocess.Popen at 0x7f47bcbf6668> In [8]: Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile Installed Packages GeoIP.x86_64

我想从shell命令中检索输出

In [7]: subprocess.Popen("yum list installed", shell=True)
Out[7]: <subprocess.Popen at 0x7f47bcbf6668>

In [8]: Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Installed Packages
GeoIP.x86_64                          1.5.0-11.el7                     @anaconda
NetworkManager.x86_64  
....
[7]中的
:subprocess.Popen(“已安装的yum列表”,shell=True)
出[7]:
在[8]中:加载的插件:FastTestMirror
从缓存的主机文件加载镜像速度
已安装的软件包
GeoIP.x86_64 1.5.0-11.el7@anaconda
NetworkManager.x86_64
....
结果输出到控制台


我如何将输出保存到一个名为“installed_tools”的变量

尝试将
stdout
和/或
stderr
设置为

同样,最好使用
Popen.communicate()
,以防stderr需要读取并被阻塞。(谢谢你,尤塔哈海德)


为什么要使用
proc.stdout.read()
而不是
proc.communicate()[0]
?@Utah两者都可以。@iBug,不,它们不都可以--
proc.stdout.read()
如果需要先读取stderr,就会死锁,如果出现大量错误,就会发生这种情况。谢谢你们两位。我忘了那一点。
import subprocess as sp

proc = sp.Popen("yum list installed", shell=True, stdout=sp.PIPE, stderr=sp.PIPE)

out = proc.stdout.read().decode('utf-8')
print(out)
import subprocess as sp

cp = sp.Popen("yum list installed", shell=True, stdout=sp.PIPE, stderr=sp.PIPE).communicate()

out = cp[0].decode('utf-8')
print(out)