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

2 つのオプションがあります。

  1. 既存のコード ベースを変更する
  2. 現在の実行可能コードにラッパーを書き込む

オプション 1 を選択する場合は、プレーンでシンプルな Python コードだと思います。

standard output streamオプション 2 を選択する場合は、既存の実行可能コードを解析する必要があります。次のようなものが機能します。

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

印刷する代わりに、結果をデータ構造に保存します。たとえば、次のようなリストに保存します。

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 に答える
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 に答える