Python 3 [TypeError: 'str' object cannot be interpreted as an integer] when working with sockets

Python 3 [TypeError: 'str' object cannot be interpreted as an integer] when working with sockets

我在终端中 运行 带有 python3 的脚本,但是当我到达其中的某个点时,出现以下错误:

Traceback (most recent call last):
  File "client.py", line 50, in <module>
    client()
  File "client.py", line 45, in client
    s.send(bytes((msg, 'utf-8')))
TypeError: 'str' object cannot be interpreted as an integer

这是它引用的代码。

else :
    # user entered a message
    msg = sys.stdin.readline()
    s.send(bytes((msg, 'utf-8')))
    sys.stdout.write(bytes('[Me] '))
    sys.stdout.flush()

我阅读了 bytes() 的官方文档和另一个来源

https://docs.python.org/3.1/library/functions.html#bytes

http://www.pythoncentral.io/encoding-and-decoding-strings-in-python-3-x/

但我对解决这个问题的理解并不深入。我意识到我的 msg 是一个字符串,我需要一个整数,但我对如何转换它感到困惑。你能帮我吗,或者告诉我一个可以帮助我的消息来源?

编辑 1:我更改了行

s.send(bytes((msg, 'utf-8')))

s.send(bytes(msg, 'utf-8'))

但现在我收到以下错误:

Traceback (most recent call last):
  File "client.py", line 50, in <module>
    client()
  File "client.py", line 46, in client
    sys.stdout.write(bytes('[Me] '))
TypeError: string argument without an encoding

编辑 2:根据@falsetru 更新的答案。 使用字节文字给我

TypeError: must be str, not bytes

更改以下行:

s.send(bytes((msg, 'utf-8')))

如:

s.send(bytes(msg, 'utf-8'))

换句话说,传递一个字符串和一个编码名称而不是传递一个元组到 bytes


更新 根据问题变化:

您需要将字符串传递给 sys.stdout.write。只需传递一个字符串文字:

sys.stdout.write('[Me] ')