0

Good evening/morning,

I have been passing a lot of commands to the terminal in a python program and was wondering if there was a way of passing a command and immediately saving the printed information without having to first save it to a file and then read that file in?

For example, this is what I have been doing:

os.system("lspci -tv > results")
if Addresses[i-1] in open('results').read():

Is there a way to just store the results from lspci -tv to a variable in my program so my program isn't dependent on another file and cluttering my computer with files every time I need to use this method?

Thanks in advance.

Trever Wagenhals
  • 381
  • 5
  • 14

1 Answers1

0

Yes you can, according with this question:

import subprocess

proc = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE)
output = proc.stdout.read()

print output

Or if you want an array with the results:

import subprocess

proc = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE)
output = proc.stdout.read()
array = output.split("\n")[:-1]

for i in range(len(array)):
    print str(i) + " : " + array[i]

Docs here.

Community
  • 1
  • 1
xdola
  • 562
  • 2
  • 8
  • 23
  • I've come across this before and used it, although the functionality seems limited. If, for example I want to execute: "lspci -vvv" or "lspci -tv" as I mentioned, it throws an error message: Traceback (most recent call last): File "stdout.py", line 3, in proc = subprocess.Popen('lspci -tv', stdout=subprocess.PIPE) File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory – Trever Wagenhals Apr 05 '16 at 20:29
  • Try adding shell=True before stdout=subprocess.PIPE (looks the edit) – xdola Apr 05 '16 at 20:32
  • Thankyou, that did the trick. You saved me a lot of time poking around for this as there are so many variations of this code. – Trever Wagenhals Apr 05 '16 at 20:37