0

我对 python 和 PLC 完全陌生。我从西门子 PLC 的特定标签收到一个字节数组格式(b'\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')的字符串,我只需要获取字符串“测试”并将其显示在 GUI 中。我不知道如何从这个字节数组中拆分“测试”。谁能帮我实现它。我正在使用python 3。

该值在发送前在 PLC 软件中设置为字符串格式。我已经完成了以下代码来读取标签值

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)

我将输出作为字节数组。

(b'\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

4

2 回答 2

1

如果没有关于字符串是否总是在同一个位置或类似的东西的任何进一步信息,我只能提供这个非常静态的答案:

# 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
于 2021-10-27T12:02:39.773 回答
-1
a = '\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b = a.split("\x00")[0][2:]

会给 b 作为:

'Testing'
于 2021-10-27T14:34:28.727 回答