Skip to main content
 首页 » 编程设计

Python 3.3 与 Python 3.2 问题

2025年05月04日9qlqwjy

不知道这是否是错误,但我的脚本不再适用于 Python 3.3,而它适用于 Python 3.2。

我有一个生成器函数可以像这样从二进制文件返回字节:

def yield_record(infile, size = 1): 
 
    while True: 
        block = infile.read(size) 
 
        if len(block) == 0: 
            break 
        else: 
 
            yield (block[0], block[1:]) 

我的问题

在 Python 3.2 中,block[0] 的类型是 'int',block[1:] 的类型是 'bytes'。这符合预期。

在 Python 3.3 中,block[0] 的类型是 'str',block[1:] 的类型也是 'str'。这不是预期的,会导致接收数据的代码失败。

有人知道怎么回事吗?

这是使用生成器的代码。

with open(infilename, mode='rb') as trace_stream: 
    # create an empty list of trace records 
    trace = [] 
    record_count = 0 
 
    # iterate over each record in the binary stream 
    for record_type, record_data in yield_record(trace_stream, 
                                                 size=RECORD_LENGTH): 
        record_count += 1 
 
        try: 
            # determine what class this record belongs to 
            record_class = RECORD_CLASS[record_type] 
            # instantiate the new record 
            new_record = record_class(record_data) 
            # append this new record to our trace 
            trace.append(new_record) 
 
        except KeyError as err: 
            print("Unhandled Record Type: {0}  Record: {1}".format(record_type, record_count)) 

谢谢,

这是一个屏幕截图。

请您参考如下方法:

好的,我发现了问题。出于某种原因,当我第一次从命令行运行它时,我认为 Python3.3 解释器正在运行,因为这是我路径中的第一个解释器,但 Python 2.7 解释器必须运行。当我给出 python3.3 解释器的完整路径时,它起作用了。