Reputation: 11
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
Upvotes: 0
Views: 1155
Reputation: 174622
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))
Upvotes: 0
Reputation: 6547
You have two options,
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.
Upvotes: 1
Reputation: 369134
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)
Upvotes: 0