Reputation: 537
I'm using a LabVIEW simulator that I have connected to via the Python3 socket
Library
import socket
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip=socket.gethostbyname("127.0.0.1")
port=1234
address=(ip,port)
client.connect(address)
while True:
data = client.recv(1024)
print(data)
client.close()
The output of data is:
b'&&\r\n0108500.00\r\n01410.000000\r\n01420.000000\r\n01430.000000\r\n01440.000000\r\n01450.000000\r\n0146200.000000\r\n0147100.000000\r\n!!\r\n&&\r\n0108500.00\r\n01410.000000\r\n01420.000000\r\n01430.000000\r\n01440.000000\r\n01450.000000\r\n0146200.000000\r\n0147100.000000\r\n!!\r\n'
The simulator is outputting two constant values of 200
and 100
which I correspond to \r\n0146200.000000\r\n0147100.000000\
0146 and 0147
are tag ID's from the simulator. Whats the best way to parse this data (Lets assume for this question I only want the tagID and Value of the last two)? I've tried to output it with:
print(data.decode("utf-8", "strict"))
output:
&& 0108500.00 01410.000000 01420.000000 01430.000000 01440.000000 01450.000000 0146200.000000 0147100.000000 !! && 0108500.00 01410.000000 01420.000000 01430.000000 01440.000000 01450.000000 0146200.000000 0147100.000000 !!
Upvotes: 1
Views: 5991
Reputation: 27283
Use a regular expression to extract the keys and values:
import re
results = [
dict(re.findall(r"(\d{4})([\d.]+)", string))
for string in filter(
bool, # non-empty
data.decode("utf8", "replace").split("&&"),
)
]
Results for your data:
[{'0108': '500.00',
'0141': '0.000000',
'0142': '0.000000',
'0143': '0.000000',
'0144': '0.000000',
'0145': '0.000000',
'0146': '200.000000',
'0147': '100.000000'},
{'0108': '500.00',
'0141': '0.000000',
'0142': '0.000000',
'0143': '0.000000',
'0144': '0.000000',
'0145': '0.000000',
'0146': '200.000000',
'0147': '100.000000'}]
Upvotes: 1