Python3.6使用softScheck/tplink-smartplug遇循环报错求助
Fixing the Bytes/String Conflict in tplink-smartplug Python 3 Port
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, theencrypt()function returns a regular string, butsock_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 theencrypt()result to bytes (likeencrypt(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:
- 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. - 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
cmdvariable. - 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 skipord()and directly XOR with the key. - Valid byte appends: Instead of
chr(a)(which creates a string character), we usebytes([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
相关产品推荐
相关产品推荐

