0

我在下面有这段代码,可以打印出 WiFi 连接的链接质量和信号级别。我正在尝试将检索到的数据存储到一个变量中,以便我可以进一步处理,但我不知道该怎么做。

while True:
cmd = subprocess.Popen('iwconfig %s' % args.interface, shell=True,
                       stdout=subprocess.PIPE)
for line in cmd.stdout:
    if 'Link Quality' in line:
        print line.lstrip(' '),
    elif 'Not-Associated' in line:
        print 'No signal'
time.sleep(1)

输出示例

Link Quality=63/70  Signal level=-47 dBm
4

3 回答 3

1

你有两个选择,

  1. 修改现有代码库
  2. 在当前可执行代码上编写一个包装器

如果您选择选项 1,我想这是简单明了的 Python 代码。

如果您选择选项 2,您将需要解析standard output stream现有的可执行代码。像这样的东西会起作用:

from subprocess import getstatusoutput as gso

# gso('any shell command')
statusCode, stdOutStream = gso('python /path/to/mymodule.py')
if statusCode == 0:
    # parse stdOutStream here
else:
    # do error handling here

您现在可以解析stdOutStream使用多个字符串操作,如果您的输出具有可预测的结构,这应该不难。

于 2016-03-21T05:57:56.553 回答
0

您可以将输出解析为更友好的数据结构:

import re
results = []
while True:
    cmd = subprocess.Popen('iwconfig %s' % args.interface, shell=True,
                       stdout=subprocess.PIPE)
    for line in cmd.stdout:
       results.append(dict(re.findall(r'(.*?)=(.*?)\s+', line))
    time.sleep(1)

for count,data in enumerate(results):
    print('Run number: {}'.format(count+1))
    for key,value in data.iteritems():
        print('\t{} = {}'.format(key, value))
于 2016-03-21T06:14:47.710 回答
0

将结果保存到数据结构中,而不是打印,例如保存到如下列表中:

while True:
    result = []
    cmd = subprocess.Popen('iwconfig %s' % args.interface, shell=True,
                           stdout=subprocess.PIPE)
    for line in cmd.stdout:
        if 'Link Quality' in line:
            result.append(line.lstrip())
        elif 'Not-Associated' in line:
            result.append('No signal')

    # do soemthing with `result`
    #for line in result:
    #    line ...... 

    time.sleep(1)
于 2016-03-21T05:55:25.770 回答