2016-03-21 9 views
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 

答えて

0

の例は、以下のようなリストにexamleため、データ構造に結果を保存します。

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) 
1

次の2つのオプション、

を持っています
  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を解析することができます。

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)) 
関連する問題