【问题标题】:im triying to comunicate with telnetlib to my yeelight desk lamp我正在尝试通过 telnetlib 与我的 yeelight 台灯通信
【发布时间】:2020-02-27 08:46:23
【问题描述】:

我正在尝试使用 telnetlib 与我的 yeelight 台灯进行通信,使用如下命令:{"id":1,"method":"set_power","params":["on","smooth",500]}我得到这样的错误:

tn.write("{"id":1,"method":"set_power","params":["off","smooth",500]}")
             ^
SyntaxError: invalid syntax

我的代码是:

import time
import telnetlib
HOST ="192.168.1.100"
tn=telnetlib.Telnet(HOST,55443)
tn.write("{"id":1,"method":"set_power","params":["off","smooth",500]}")
l=tn.read_all()

【问题讨论】:

  • 您的字符串在它的旁边有双引号,所以它不能被这些相同的引号括起来。要么转义字符串中的引号("\"..."),要么使用另一种机制来引用,例如单引号',或者使用 json dict / list 对数据进行建模,并使用 json.dumps() 编组为 json。

标签: python telnetlib


【解决方案1】:

试试这个:

tn.write("""{"id":1,"method":"set_power","params":["off","smooth",500]}""")

另一种方法是:

import json 
tn.write(json.dumps({'id': 1, 'method': 'set_power', 'params': ['off', 'smooth', 500])}))

或者这个:

tn.write('{"id":1,"method":"set_power","params":["off","smooth",500]}')

重点是,你要发送一个json字符串,注意不要用"剪掉它

【讨论】:

  • 第一个我有这个错误 Traceback(最近一次调用最后):文件“off.py”,第 7 行,在 tn.write("""{"id":1 ,"方法":"set_power","params":["off","smooth",500]}""") 文件 "C:\Users\ΜιχαληςΞενακης\AppData\Local\Programs\Python\Python37\lib \telnetlib.py",第 287 行,如果 IAC 在缓冲区中写入:TypeError: 'in ' 需要字符串作为左操作数,而不是字节
  • 使用 json 转储方法。手动编写 json 字符串是一件傻事,尤其是因为您很可能希望在 python 中操作数据。
  • 使用我在 中的 json 方法需要字符串作为左操作数,而不是字节错误
  • 我认为您需要发送字节而不是普通字符串。试试看:tn.write(json.dumps({'id': 1, 'method': 'set_power', 'params': ['off', 'smooth', 500])}).encode("utf8"))
猜你喜欢
  • 1970-01-01
  • 2022-11-17
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多