I am completely new to python and PLC. I received a String from a particular tag of Siemens PLC in the byte array format like this (b'\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
I need to take only the String "Testing" and display it in the GUI. I don't know how to Split "Testing" from this byte array. Can anyone please help me in achieving it. I am using python 3.
The value is set to String format in PLC software before sending. I have done the following code for reading the tag value
import snap7
from snap7.util import *
import struct
import snap7.client
import logging
DB_NUMBER = ***
START_ADDRESS = 0
SIZE = 255
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
plc = snap7.client.Client()
plc.connect('My IP address',0,0)
plc_info = plc.get_cpu_info()
print(plc_info)
state = plc.get_cpu_state()
print(state)
db = plc.db_read(DB_NUMBER, START_ADDRESS, SIZE)
print(db)
I am getting the output as a byte array.
(b'\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
CodePudding user response:
Without any further information on whether the string is always at the same position or stuff like that, I can only provide this very static answer:
# The bytearray you gave us
barray = bytearray(b'\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
# Start at index 2, split at first occurrence of 0byte and decode it to a string
print(barray[2:].split(b"\x00")[0].decode("utf-8"))
>>> Testing
CodePudding user response:
a = '\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b = a.split("\x00")[0][2:]
Will give b as:
'Testing'