在Python中使用exec循环

2 投票
4 回答
4800 浏览
提问于 2025-04-17 05:08

我正在尝试运行一个循环,这个循环会逐行处理一个命令的输出。比如:

for line in exec 'lspci | grep VGA':
    count = count + 1

我想看看系统里安装了多少块显卡。但是在循环的语法上似乎有问题。

我需要导入一个库来使用exec吗?还是我用错了?或者两者都有?

谢谢

4 个回答

0

你想使用 popen(或者类似的东西)。exec 是用来执行 Python 代码的。例如:

exec('x = 4')
print x  # prints 4

另外,你缺少了括号,这样写是不符合语法的。exec 是一个函数:

for line in exec('lspci | grep VGA'):  # this still does not do what you want
    count = count + 1

你可以使用 wc -l 一下子就获取行数。

import os
count = os.popen('lspci | grep VGA | wc -l').read()
5

关键字 exec 用来执行 Python 代码。它不会启动新的进程。

可以试试 subprocess 模块。

lines = subprocess.check_output(["lspci"]).split('\n')
count = sum('VGA' in line for line in lines)
6

exec 是用来执行 Python 代码的,而不是用来执行外部命令。如果你想执行外部命令,可以使用 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()

在我的电脑上,这会输出

01:00.0 VGA compatible controller: nVidia Corporation GF104 [GeForce GTX 460] (rev a1)

撰写回答