【问题标题】:TypeError: str, bytes or bytearray expected, not listTypeError: str, bytes or bytearray expected, not list
【发布时间】:2018-04-21 13:17:14
【问题描述】:

所以我试图从文本文件中提取一些 IP 并在套接字连接中使用该列表。我的问题是我不断收到以下错误:

TypeError: str, bytes or bytearray expected, not list

这是我使用的代码:

    import socket

     ips = open('list.txt', 'r').readlines()

     def displayType(sec_type):
       switcher = {
        0: "1",
        1: "2",
        2: "3"
       } 
       print(' type: ' + str(sec_type) + ' (' + switcher.get(sec_type,"Not defined by IETF") +')' )

    try:
       def check(ip,port):
         link = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
         link.connect((ip,int(port)))
         link_ver = link.recv(12)
         print(link_ver)

         link.send(link_ver)
         nb_sec_types = ord(link.recv(1))
         print("types: " + str(nb_sec_types))

    check(ips,"80")

如果有人知道如何使用列表中的 ip,那就太好了。

【问题讨论】:

  • 错误很直观.. 哪一行引发了错误?
  • 对此感到抱歉。它的行有:check(ips,"5900") & 还有:link.connect((ip,int(port)))
  • 对象ips是一个列表。当您调用link.connect 时,您最终会传递list 作为参数,但它表示link.connect 需要一个字符串。您可以通过遍历 ips 列表来解决此问题,例如:for ip in ips: check(ip, "80)
  • 太棒了,谢谢你,我做了改变,它正在工作。

标签: python python-3.x python-sockets


【解决方案1】:

改变

check(ips, "80) 

为

for ip in ips: 
    check(ip, "80) 

link.connect 需要一个唯一的 ip,而您正在传递一个 ips 列表。

【讨论】:

    【解决方案2】:

    readlines() 方法读取到 EOF 并返回包含行的列表。所以你得到了一个ips列表。您将需要遍历此列表并在每次迭代时调用 check()。

    另外,您使用了try 块,而没有except 或finally。这将导致错误。

    您可以将 catch() 放在 try-except 块中:

    try:
     catch(ip, port)
    except Exception as e:
     print(str(e))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-12
      • 2020-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多