【问题标题】:TypeError: 'in <string>' requires string as left operand, not bytes,pythonTypeError:'in <string>' 需要字符串作为左操作数,而不是字节,python
【发布时间】:2021-08-22 23:40:32
【问题描述】:

我在执行一个占用telnet的python脚本时出错,在执行时我得到了我最后指出的错误。这个错误是由我在代码中提到的那一行执行的,但我找不到任何解决方案,希望您能帮我解决。

代码:

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)

错误:

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

【问题讨论】:

    标签: python byte telnet


    【解决方案1】:

    这里的问题是,在telnetlib.py 中,IAC 的类型为 bytes,但您的 command+"\n\n" 的类型为 str。您可能还需要通过str.encode() 将传递给tn.write() 的任何字符串转换为字节字符串

    试试:

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

    【讨论】:

    • 解决了,非常感谢
    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多