【问题标题】:ValueError: invalid literal for int() with base 10: b'1\n5\n'ValueError: int() 以 10 为底的无效文字:b'1\n5\n'
【发布时间】:2019-04-30 14:51:19
【问题描述】:

我有一个 python 程序,它通过 TCP-IP 连接到一个 matlab 程序,其中 python 代码是客户端,它的接收数字如下:

1
2
5
6
7
etc..

(我收到的数字只有:1、2、3、4、5、6、7)以随机顺序排列。我得到的错误是:ValueError:int() 的无效文字,基数为 10:b'1\n5\n'。我的代码是:

# TCP connection
try:
    so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
    print ("socket creation failed with error %s" %(err))

#default port for socket
port = 2000

# default time out
#so.settimeout(1000000)

try:
    host_ip = socket.gethostbyname('localhost')
except socket.gaierror:
    # this means could not resolve the host
    print ("there was an error resolving the host")
    sys.exit()

# connecting to the server
so.connect((host_ip,port))

# MATLAB INFORMATION FOR OFFLINE EXPERIMENT
Nepoch = 10  #nr de epochs por trial
Nwords = 7   #nr de palavras (SIM, NAO, FOME, SEDE, URINAR, AR, POSICAO)
SeqTrain = [1, 3, 5, 7, 2, 4, 6, 1, 3, 5, 7, 2, 4, 6] #sequencia offline de treino

# read the TCP sequence received
def sequencia():
    num = 0
    for i in range(0,999):
        s = so.recv(port) #+ b'\n' #since the sequence received is : 1\n 2\n 5\n etc
        i = int(s)
        #print(i)
        #feedbak offline (for the user to know which are the words)
        if (num in (0, Nepoch*Nwords+1, Nepoch*Nwords*2+2, Nepoch*Nwords*3+3, Nepoch*Nwords*4+4, Nepoch*Nwords*5+5,\
                    Nepoch*Nwords*6+6)):
            labels1[i-1].configure(foreground="white")
            root.update()
        elif (num in (Nepoch*Nwords*7+7, Nepoch*Nwords*8+8, Nepoch*Nwords*9+9, Nepoch*Nwords*10+10,\
                     Nepoch*Nwords*11+11, Nepoch*Nwords*12+12, Nepoch*Nwords*13+13)):
            labels2[i-1].configure(foreground="white")
            root.update()
        else:
            labels[i-1].configure(background="green",foreground="red")
            root.update()
            winsound.PlaySound(sounds[i-1], winsound.SND_FILENAME)
            labels[i-1].configure(background="gray",foreground="white")
            root.update()
        num = num + 1

我收到的数字是在 matlab 程序中实时生成的。问题是当我在 matlab 中使用标准值进行模拟时,python 程序工作得很好,这让我相信这是因为 matlab 中生成的实时值。

此外,当我离线评论#feedbak 的部分(让用户知道哪些是单词)直到最后时,程序会收到数字并且 i = int (s) 没有任何问题,只有当我取消注释时其余的它给了我错误。 当我打印我收到的值时:b'1\n' b'7\n' b'4\n' b'2\n' b'6\n' b'3\n' b '1\n' b'5\n' (等等)->它从不说它同时接收 2 个值,就像我取消注释程序的其余部分时那样

我发布的所有 python 程序,适用于前 2/3 的数字,然后给我错误,这是回溯:

>>> 
 RESTART: C:\Users\meca\Desktop\Python_Exercises\seq_tcp_offline-TCP-CLIENT.py 
b'1\n'
b'7\n'
b'4\n'
Traceback (most recent call last):
  File "C:\Users\meca\Desktop\Python_Exercises\seq_tcp_offline-TCP-CLIENT.py", line 139, in <module>
    sequencia()
  File "C:\Users\meca\Desktop\Python_Exercises\seq_tcp_offline-TCP-CLIENT.py", line 44, in sequencia
    i = int(s)
ValueError: invalid literal for int() with base 10: b'2\n6\n'

这对我来说很奇怪,你们有什么想法吗?非常感谢

【问题讨论】:

  • 在询问产生异常的代码时,请始终在问题中包含完整的 Traceback。复制 Traceback 并将其粘贴到问题中,然后将其格式化为代码(选择它并键入 ctrl-k)。

标签: python tcp real-time


【解决方案1】:

\n 是换行符。 int() 在字节对象中有多个换行符时遇到问题。

后跟换行符的单个数字可以转换。

>>> b = b'1\n'
>>> int(b)
1

当您收到由换行符分隔的 流 数字时,您需要在转换之前在空格上拆分字节对象。

>>> b = b'1\n5\n'
>>> b.split()
[b'1', b'5']
>>> for c in b.split():
...     print(int(c))

1
5
>>>

或

>>> [int(n) for n in b.split()]
[1, 5]
>>> 

或者,您可以尝试在每次迭代中仅读取 2 个字节。目前,您将 2000 的值传递给 buffsize 参数。

s = so.recv(2)

您可能希望对此进行测试以确保您不使用数据 - 如果您一次只读取 2 个字节,我不知道套接字如何处理堆积的数据。 .

【讨论】:

  • 您好,非常感谢您的回答,成功了!但现在我在 matlab 和 python 程序之间有一个巨大的延迟!你知道有什么办法可以解决这个延迟吗?因为它是实时程序,所以时间安排非常重要。非常感谢
  • ...now i have a huge delay... - 我真的无法评价那个说法。这听起来像是一个单独的问题,所以你应该发布一个新问题,细节很重要——比如确定瓶颈是什么。 - 首先你可能想用python socket slow搜索。
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2018-09-09
  • 2020-01-04
  • 2010-12-22
  • 2011-07-07
  • 2019-10-14
相关资源
最近更新 更多