Storing printed data into variables

1.1k Views Asked by At

I have this code below that prints out the Link Quality & Signal Level of WiFi connection. I'm trying to store the data retrieved into a variables so I could process further but I'm stuck having no idea how to do so.

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)

Example of the output

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

There are 3 best solutions below

0
falsetru On

Instead of printing, save the result into data structure, for examle into list like following:

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)
0
psiyumm On

You have two options,

  1. Modify the existing code base
  2. Write a wrapper over the current executable code

If you go for option 1, I guess it is plain and simple Python code.

If you go for option 2, you will want to parse the standard output stream of the existing executable code. Something like this would work:

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

You can now parse the stdOutStream using multiple string operations which shouldn't be difficult if your outputs have a predictable structure.

0
Burhan Khalid On

You can parse the output into a more friendly data structure:

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