1

I'd like to retrieve the output from a shell command

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  
....

The results are output to the console,

How could I hold the output to a variable saying "installed_tools"?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

1

Try setting stdout and/or stderr to subprocess.PIPE.

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)

As suggested in comments, it's better to use Popen.communicate() in case stderr needs reading and gets blocked. (Thanks UtahJarhead)

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)
iBug
  • 35,554
  • 7
  • 89
  • 134