Mauricio Romero
Mauricio Romero

Reputation: 39

TypeError: 'in <string>' requires string as left operand, not bytes,python

I have an error when executing a script made in python that occupies telnet, at the moment of executing I get the error that I indicate at the end. This error is executed by the line that I mention in the code but I could not find any solution , I hope you can help me solve it.

Code:

def simulate(location,loggers,sensors,host,port,interval):
   '''Simulate the reception of oxygen data to cacheton '''
   temp_range = MAX_TEMP - MIN_TEMP
   o2_range   = MAX_O2 - MIN_O2
   t = 0.0
   steps = -1
   while 1:
       for logger in loggers:
           for sensor in sensors:
               temp1 = random.random() * temp_range + MIN_TEMP
               oxi1  = random.random() * o2_range + MIN_O2
               unix_time = int(time.time())
               command = "PUT /%s/oxygen/%i/%i/?oxy=%.1f&temp=%.1f&time=%i&depth=1&salinity=32&status=1" % (location, logger, sensor, oxi1, temp1, unix_time)
               print (command)
               tn = telnetlib.Telnet(host,port)
               tn.write(command+"\n\n")#here is theerror
       
               tn.write("\n")
               tn.close()
       t += interval
       if steps > 0:    steps -= 1
       if steps == 0:   break
       time.sleep(interval)

Error:

Traceback (most recent call last):
  File "simulate_oxygen_cacheton.py", line 57, in <module>
    simulate(args.location, range(loggers), range(sensors), args.host, args.port, args.interval)
  File "simulate_oxygen_cacheton.py", line 29, in simulate
    tn.write(command+"\n\n")
  File "/home/mauricio/anaconda3/lib/python3.7/telnetlib.py", line 287, in write
    if IAC in buffer:
TypeError: 'in <string>' requires string as left operand, not bytes

Upvotes: 1

Views: 1981

Answers (1)

myz540
myz540

Reputation: 559

The problem here is that in telnetlib.py, IAC is of type bytes but your command+"\n\n" is of type str. You may also need to convert any strings you are passing to tn.write() into byte strings by feeding them through str.encode()

Try:

tn.write(str.encode(command+"\n\n"))

Upvotes: 1

Related Questions