ord function in python2.7 and python 3.4 are different?
我一直在运行一个脚本,在其中使用
在python 3.4中,情况并非如此。这是产生的错误的输出:
1 2 3 4 | Traceback (most recent call last): File"udpTransfer.py", line 38, in <module> buf.append(ord(c)) TypeError: ord() expected string of length 1, but int found |
当我查看两个文档时,都将ord函数解释为做同样的事情。
这是我用于两个python版本的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | import socket,sys, ast , os, struct from time import ctime import time import csv # creating the udo socket necessary to receive data sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) ip = '192.168.10.101' #i.p. of our computer port = 20000 # socket port opened to connect from the matlab udp send data stream server_address = (ip, port) sock.bind(server_address) # bind socket sock.settimeout(2) # sock configuration sock.setblocking(1) print('able to bind') ii = 0 shotNummer = 0 client = '' Array = [] byte = 8192 filename = time.strftime("%d_%m_%Y_%H-%M-%S") filename = filename + '.csv' try : with open(filename,'wb') as csvfile : spamwriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) # spamwriter.writerow((titles)) # as long as data comes in, well take it while True: data,client = sock.recvfrom(byte) buf = [] values = [] for c in data: # print(type(c)) buf.append(ord(c)) if len(buf) == 4 : ### |
有谁能解释为什么python3.4会说
您正在将整数传递给Python 3中的
1 2 3 4 5 6 | >>> for byte in b'abc': ... print(byte) ... 97 98 99 |
来自
While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers[.]
和
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b,
b[0] will be an integer [...].
在Python 2中,
您可以改用
1 2 | for c in bytearray(data): # c is now in integer in both Python 2 and 3 |
在这种情况下,您根本不需要使用
我认为区别是在Python 3中,
Python 2.7 recvfrom
Python 3.5 recvfrom