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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 <module> 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
Try adding shell=True before stdout=subprocess.PIPE (looks the edit)
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.