【问题标题】:Splitting a String from byte array从字节数组中拆分字符串
【发布时间】:2021-12-12 17:12:47
【问题描述】:

我对 python 和 PLC 完全陌生。我从 Siemens 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')

【问题讨论】:

  • PLC 通常在文本之前发送字符串的长度。在这种情况下 \x07 因为“测试”有七个字符。
  • @lcecl Yah 没错

标签: python-3.x logging plc snap7


【解决方案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

【讨论】:

  • 或者数字节,barray[2:9].decode("utf-8")直接切片得到字符串。
  • 当然,如果字符串总是具有相同的长度。
  • @js-on 。字符串的长度会有所不同,但显示的位置保持不变。
  • @js-on 。非常感谢我使用此代码print(barray[2:].split(b"\x00")[0].decode("utf-8")) >>> Testing 得到了输出
【解决方案2】:
a = '\xfe\x07Testing\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b = a.split("\x00")[0][2:]

将 b 设为:

'Testing'

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多