Python 使用任意变量保存subprocess.Popen的输出
我想从shell命令中检索输出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
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)