2017-02-20 40 views
0

EDIT到格式:我正在此错误 “类型错误:STR()采用至多1参数(2给出)” 在 “client_response” 可变

这是原来的代码

from __future__ import print_function 
import socket 
import sys 

def socket_accept(): 
    conn, address = s.accept() 
    print("Connection has been established | " + "IP " + address[0] + "| Port " + str(address[1])) 
    send_commands(conn) 
    conn.close() 

def send_commands(conn): 
    while True: 
     cmd = raw_input() 
     if cmd == 'quit': 
      conn.close() 
      s.close() 
      sys.exit() 
     if len(str.encode(cmd)) > 0: 
      conn.send(str.encode(cmd)) 
      client_response = str(conn.recv(1024), "utf-8") 
      print(client_response, end ="") 

def main(): 
    socket_accept() 
    main() 

我我得到这个错误“类型错误:STR()采用最多1参数(2给出)”在“client_response”变量

+0

请格式化您的代码并解释您正在尝试做什么以及期望的结果。 –

+0

好吧现在就这样做 –

回答

4

你有你的错误在这里:

client_response = str(conn.recv(1024), "utf-8") 

它只是更改为:

client_response = str(conn.recv(1024)).encode("utf-8") 
+0

您的_solution_中的括号不匹配 –

+1

对,修正了它 –

+0

这是否解决了您的问题? –

2

在第二到你传递两个参数到str函数最后一行,虽然str功能只在Python 2.一个参数,它实际占用在Python 3三个参数

https://docs.python.org/2.7/library/functions.html?highlight=str#str https://docs.python.org/3.6/library/functions.html?highlight=str#str

所以,你要么试图在Python解释器2至inadvertaetly运行python 3代码或你正在寻找在错误的语言文档。

因此,要么使用@ franciscosolimas的答案,如果您使用的是Python 2,或者确保您使用的是Python 3,如果后者您可能还想添加关键字参数,以确保知道发生了什么未来

client_response = str(conn.recv(1024), encoding="utf-8") 
+0

如果是这种情况,我该如何解决我的问题? –

相关问题