1

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

1 Answer 1

1

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'}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.