python - 当我尝试在 Python 中写入数据时,文件有时会打开,有时会关闭
问题描述
在我的主文件中,我调用以下函数将相同的数据写入二进制文件:
主文件
writeOutputFile(param1, param2, param3)
在file_a.writeOutputFile
我用 with 语句打开我的输出文件并调用函数file_b.writeReference
:
文件_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
对象
文件_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__
and__exit__
方法,以便您可以看到上下文管理器何时进入和退出(文件关闭?)。也许将更多日志记录添加到程序的其他部分以获得更细粒度的 time-history。使用假文件或什至与您的真实文件更隔离的东西进行一些测试运行(我这么说主要是因为我不知道使用子类的后果,所以您应该小心)。这是一个例子:
import io
class B(io.FileIO):
def __enter__(self):
print(f'\tcontext manager entry - file:{self.name}')
return super().__enter__()
def __exit__(self,*args,**kwargs):
print(f'\tcontext manager exiting - file:{self.name}')
super().__exit__(self,*args,**kwargs)
In [32]: with B('1.txt','wb') as f:
...: f.write(b'222')
...:
context manager entry - file:1.txt
context manager exiting - file:1.txt
In [33]:
推荐阅读
- c# - 通过使用最多 P 个点获得字典上可能最小的字符串
- angular - Firebase 是否足以作为 Angular 网站的后端?
- javascript - 单击时 HTML/CSS/JS 更改多个按钮的颜色
- javascript - 映射对象的 javascript 数组以修改字符串属性
- assembly - 为什么 Rust final 二进制文件中有这些无用的指令?
- sql-server - 处理可以采用空参数的过程
- javascript - 在本地下载 Earth Engine 图像
- vue.js - Nuxt:在page.vue中根据数据动态设置布局
- python-3.x - 将椭圆拟合到点:为什么椭圆适合某些数据集,而对于其他数据集则有 90 度的偏移?
- sql - 为什么 SQL 触发器没有使用电子邮件的权限?