在主文件中,我调用以下函数将相同的数据写入二进制文件:
主.py
writeOutputFile(param1, param2, param3)
在file_a.writeOutputFile
中,我用with语句打开输出文件
并调用函数file_b.writeReference
:
文件\u 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
对象
文件\u 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 -
关于错误可能在哪里有什么提示吗?我真的不明白为什么它有时有效,有时无效。 先谢谢你
不是答案。
诊断工具:
子类
io.FileIO
;重写添加日志的__enter__
和__exit__
方法,以便您可以看到上下文管理器何时进入和退出(文件关闭?)。也许可以向程序的其他部分添加更多日志,以获得更细粒度的时间历史。用一个假文件或者一些与真实文件隔离的东西来做一些测试运行(我这么说主要是因为我不知道使用子类的后果,所以你应该小心)。举个例子:这个问题与docker容器有关,它处理我在上面共享的代码。 我是Docker的新手,所以我使用以下命令来构建容器(我有3个微服务):
如果没有重新创建容器(源代码中没有更改),那么第二次重新运行之前停止的容器时,我的文件最后关闭了。你知道吗
如果我强制重新创建容器(在不需要更改源代码的情况下):
我没有更多的错误。你知道吗
相关问题 更多 >
编程相关推荐