文件有时是打开的,当我尝试在Python中写入数据时有时会关闭

问题描述 投票:-1回答:1

在我的主文件中,我调用以下函数将相同的数据写入二进制文件:

main.py

writeOutputFile(param1, param2, param3)

file_a.writeOutputFile中,我在with语句中打开输出文件并调用函数file_b.writeReference

file_a.py

@singleton
class BitstreamToFile:
    def __init__(self, outfile):
        self.outfile = outfile
        self.cache = ''

    def add(self, data, length):
        s = ''
        if (type(data) == str):
            log.info("string %s \n "%data)
            for char in data:
                b = bin(ord(char))[2:]
                s = s + "{:0>8}".format(b)
        else:
            s = bin(data)[2:]
            if (len(s) < length):
                resto = length - len(s)
                for _ in range(0, resto):
                    s = '0' + s
        s = s[0:length]
        self.cache = self.cache + s

        self.flush()

    def writeByteToFile(self):
        if (len(self.cache) < 8):
            raise ("Not enough bits to make a byte ")
        data = int(self.cache[:8], 2)
        log.info("writeByteToFile %s " % data)
        self.outfile.write(struct.pack('>B', data))
        self.cache = self.cache[8:]

    def flush(self, padding=False):
        while (len(self.cache) >= 8):
            log.info("BEF flush len(self.cache) %s"%len(self.cache))
            self.writeByteToFile()
            log.info("AFT flush len(self.cache) %s"%len(self.cache))

        if (padding):
            self.cache = "{:0<8}".format(self.cache)
            self.writeByteToFile()

def writeOutputFile(param1, param2, param3):
    [..]
    with open(OUTPUT_FILE, 'wb') as out_file:
       writeReference(out_file, param2, param1)

file_B.writeReference中实例化我的BitstreamToFile对象

file_b.py

def writeReference(out_file, param2, param1):
    bitstream = file_a.BitstreamToFile(file)
    log.debug ("write key && length")
    bitstream.add("akey", 32)
    bitstream.add(0, 64)
    [..]

当我第一次编译并执行时,没有任何错误。第二次我得到:

# log from `file_B.writeReference`   
write key && length
# log from file_a.bitstream.flush
BEF flush len(self.cache) 32
#log from file_a.bitstream.writeByteToFile
writeByteToFile 114

然后代码崩溃:

Exception on /encode [POST]
[..]
File "/src/file_a.py", line 83, in flush
self.writeByteToFile()
File "/src/file_a.py", line 73, in writeByteToFile
self.outfile.write(struct.pack('>B', data))
ValueError: write to closed file
"POST /encode HTTP/1.1" 500 -

关于错误可能在哪里的任何提示?我真的不明白为什么有时候有时候行得通,有时候却行不通。预先谢谢你

python python-3.x
1个回答
0
投票

没有答案。

诊断工具:子类io.FileIO;覆盖添加日志记录的__enter____exit__方法,以便您可以查看上下文管理器何时进入和退出(文件已关闭?)。也许将更多日志记录添加到程序的其他部分,以获得更细粒度的[[time-history
© www.soinside.com 2019 - 2024. All rights reserved.