I am trying to run a for loop that goes through each line of the output of a command. For ex:
for line in exec 'lspci | grep VGA':
count = count + 1
To try and get the amount of video cards installed in a system. But it doesn't seem to line the syntax on the for loop line.
Do I have to import a library for exec? Or am I using it wrong? Or both?
Thanks
exec executes Python code, not an external command. You're looking for subprocess.Popen():
import subprocess
p = subprocess.Popen('lspci', stdout=subprocess.PIPE)
for line in p.stdout:
if 'VGA' in line:
print line.strip()
p.wait()
On my box, this prints out
01:00.0 VGA compatible controller: nVidia Corporation GF104 [GeForce GTX 460] (rev a1)
The keyword exec executes Python code. It does not start new processes.
Try the subprocess module instead.
lines = subprocess.check_output(["lspci"]).split('\n')
count = sum('VGA' in line for line in lines)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With