【发布时间】: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)。