I'm writing code to send and receive messages in python using a GSM modem.
Whenever a new message is received I get the following response in a list x after reading from a serial port object.
+CMTI: "SM",0 # Message notification with index
I'm polling for this indication and I've made use of list comprehensions to check whether I have received the above response
def poll(x):
regex=re.compile("\+CMTI:.......")
[m for l in x for m in [regex.search(l)] if m]
This seems to be working however I want to add a print statement whenever a match is found like
print "You have received a new message!"
How can I combine the print statement with the above?
With a normal for
loop, it can be done like this:
def poll(x):
regex = re.compile("\+CMTI:.......")
lst = []
for l in x:
for m in [regex.search(l)]:
if m:
lst.append(m)
print "You have received a new message!"
Note that this list isn't being stored anywhere (outside the function scope) - perhaps you want to return
it.
As a side note, the hacky solution:
from __future__ import print_function
def poll(x):
regex = re.compile("\+CMTI:.......")
[(m, print("You have received a new message!"))[0] for l in x for m in [regex.search(l)] if m]
But this is very unpythonic - use the other version instead.