0

im triying to comunicate with telnetlib to my yeelight desk lamp with commands like this:{"id":1,"method":"set_power","params":["on","smooth",500]} and im getting errors like this:

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

and my code is:

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()
  • Your string has double quotes in side it, so it can't be enclosed by those same quotes. Either escape the quotes in your string ( `"\"..."` ), use another mechanism to enquote, like single quotes `'`, or model the data with json dict / list and marshal to json with `json.dumps()`. – erik258 Nov 01 '19 at 00:25

1 Answers1

1

try this :

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

Another way would be this :

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

Or this :

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

The point is, you have to send a json string, and be careful not to cut it using "

Loïc
  • 11,804
  • 1
  • 31
  • 49
  • with the first i have this error Traceback (most recent call last): File "off.py", line 7, in tn.write("""{"id":1,"method":"set_power","params":["off","smooth",500]}""") File "C:\Users\Μιχαλης Ξενακης\AppData\Local\Programs\Python\Python37\lib\telnetlib.py", line 287, in write if IAC in buffer: TypeError: 'in ' requires string as left operand, not bytes – mich xen Nov 01 '19 at 00:30
  • 1
    Use the json dumps method. Writing json strings by hand is a fool's errand, especially because you'll want to manipulate the data in python most likely. – erik258 Nov 01 '19 at 00:31
  • with the json method i have 'in ' requires string as left operand, not bytes error – mich xen Nov 01 '19 at 00:35
  • I think you need to send bytes instead of a common string. Try : ```tn.write(json.dumps({'id': 1, 'method': 'set_power', 'params': ['off', 'smooth', 500])}).encode("utf8"))``` – Loïc Nov 01 '19 at 01:40