I’m trying to capture data coming across a serial in a python script. The stream ends with a ‘#’ and the stream can contain letters, numbers, many other special characters and new lines. I’d like to capture all characters and place them in a file when it finishes. I’m not sure, however, if my re is correct. Is
re.match("[A-Za-z0-9,.$:<>&*=-]", char, re.DOTALL)
going to capture all letters, numbers, and ,.$:<>&*=- characters as well as newlines? Can I simply add each char as it comes across, place it in a list and then later write the list t a file like so:
while 1:
# must handle 'exceptions' - IE blank data....
try:
if s.inWaiting():
val = s.read(s.inWaiting())
for char in val:
if re.match("[A-Za-z0-9,.$:<>&=-]", char, re.DOTALL):
chunk += char
print char
# handle end of stream
#if char is '#':
if re.match("#", char):
f = open('./report', 'w')
f.write(chunk)
sys.exit()
Currently it is grabbing all I expect but it does not appear to be grabbing the new lines as the resulting file does not contain any…
Even though you’re using
re.DOTALL, your regex doesn’t actually use the dot operator. Changing line 7 to the following should work as you expect:Works for both *nix based, and PC based newline encodings, as
\rwill simply be ignored by the regex.