You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3.6使用softScheck/tplink-smartplug遇循环报错求助

Hey there, let's break down this frustrating back-and-forth error you're stuck with—it all boils down to Python 3's strict separation between strings (str) and byte objects (bytes), which the original Python 2-era code from the softScheck/tplink-smartplug repo doesn't account for.

Let's unpack the dual errors:

  • First error: bytes-like object is required
    When you run the original code, the encrypt() function returns a regular string, but sock_tcp.send() expects a byte object (since socket operations in Python 3 work exclusively with bytes).
  • Second error: ord() expected string of length 1, but int found
    If you try to fix the first error by encoding the encrypt() result to bytes (like encrypt(cmd).encode()), you'll hit this because the function was written to handle string characters, not byte values (which are integers in Python 3).

The Fix: Update encrypt() for Python 3

Here's a revised version of the function that handles both string inputs and returns the byte object sockets need, eliminating both errors:

def encrypt(string):
    key = 171
    # Initialize a byte object instead of a string for the result
    result = b"\x00\x00\x00\x00"
    # Convert input string to bytes if needed
    if isinstance(string, str):
        string = string.encode('utf-8')
    for byte_val in string:
        # byte_val is already an integer (no need for ord())
        a = key ^ byte_val
        key = a
        # Append the new byte to the result
        result += bytes([a])
    return result

How to use it:

Your command line stays the same—just pass the string cmd to encrypt(), and the function handles converting it to bytes internally:

cmd = '{"system":{"set_relay_state":{"state":0}}}'
sock_tcp.send(encrypt(cmd))

Why this works:

  1. Byte-first initialization: We start with b"\x00\x00\x00\x00" (a byte object) instead of a string, so all subsequent appends build a valid byte result.
  2. Input flexibility: The function checks if the input is a string and converts it to UTF-8 bytes automatically, so you don't have to adjust your cmd variable.
  3. No more ord(): When iterating over a byte object in Python 3, each element is an integer representing the byte's value—so we can skip ord() and directly XOR with the key.
  4. Valid byte appends: Instead of chr(a) (which creates a string character), we use bytes([a]) to create a single-byte object that can be safely added to the result.

This resolves both errors in one go by aligning the code with Python 3's string/byte rules.

内容的提问来源于stack exchange,提问作者Brent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:56:04