Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using exec in a for loop in python

Tags:

python

exec

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

like image 972
Danny Avatar asked Apr 20 '26 20:04

Danny


2 Answers

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)
like image 111
NPE Avatar answered Apr 22 '26 09:04

NPE


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)
like image 43
Mark Byers Avatar answered Apr 22 '26 08:04

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!