草庐IT

bytes_write

全部标签

python - 模拟调用 write()

我有一个需要将字符串写入文件的记录器类。所以,我有这样的方法:defwrite_to_file(self,string):self.__file_handle.write(string)请注意,错误处理已被删除。显然,我想在不写入文件的情况下进行测试。因此通过Mock进行模拟.我看过this这解释了如何模拟打开,但它在这里对我没有帮助——我在__init__中打开file_handle。现在,我可以在setUp()中执行此操作,但mock_open似乎在setUp之后超出了范围,因此在测试用例中没有用。您将如何使用Mock编写测试方法来测试write_to_file方法?

python - 使用 Python open().write() 将文件写入磁盘是否确保数据可用于其他进程?

一个Python进程将状态更新写入文件以供其他进程读取。在某些情况下,状态更新会在循环中重复且快速地发生。最简单和最快的方法是在一行中使用open().write():open(statusfile,'w').write(status)另一种方法是使用四行将数据强制写入磁盘。这会显着降低性能:f=open(self.statusfile,'w')f.write(status)os.fsync(f)f.close()我并不是要防止操作系统崩溃。那么,该方法是否将数据强制写入操作系统缓冲区,以便其他进程在从磁盘打开文件时读取最新的状态数据?或者,我需要使用os.fsync()吗?

python - 如何将换行符添加到 file.write() 的末尾?

我有一个简单的python脚本,它输出到author.json文件。问题是它没有在文件末尾包含换行符。在author.json末尾添加换行符的最佳方法是什么?#!/usr/bin/envpythonimportjsonwithopen('input.json','r')ashandle:data=json.load(handle)output=open('author.json','w')author={}forkey,valueindata.items():ifkey=='id':author['id']=valueoutput.write(json.dumps(author,ind

python - "Expected type ' Union[str, bytearray] ' got ' int ' instead"write 方法警告

我的脚本使用预先生成的数据模式逐block写入文件:#Datapatterngeneratordefget_random_chunk_pattern():return''.join(random.choice(ascii_uppercase+digits+ascii_lowercase)for_inrange(8))....#DedupChunkclassCTOR:classDedupChunk:def__init__(self,chunk_size,chunk_pattern,chunk_position=0,state=DedupChunkStates.PENDING):self.

python - 操作系统错误 : raw write() returned invalid length when using print() in python

我正在使用pythontensorflow训练一个模型来识别python中的图像。但是当我尝试从github执行train.py时出现以下错误Traceback(mostrecentcalllast):File"train.py",line1023,intf.app.run(main=main,argv=[sys.argv[0]]+unparsed)File"C:\Users\sande\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\platform\app.py",line48,inrun_sys.exit

python - Unicode解码错误: 'utf8' codec can't decode byte "0xc3"

在python2.7中我有这个:#-*-coding:utf-8-*-fromnltk.corpusimportabcwithopen("abc.txt","w")asf:f.write("".join(i.words()))然后我尝试在Python3中阅读此文档:withopen("abc.txt",'r',encoding='utf-8')asf:f.read()只为得到:File"C:\Python32\lib\codecs.py",line300,indecode(result,consumed)=self._buffer_decode(data,self.errors,fin

python 3 : reading bytes from stdin pipe with readahead

我想读取字节。sys.stdin以文本模式打开,但它有一个可用于读取字节的缓冲区:sys.stdin.buffer.我的问题是,当我将数据通过管道传输到Python时,如果我想要预读,我似乎只有2个选项,否则我会得到一个io.UnsupportedOperation:Fileorstreamisnotseekable.从sys.stdin读取缓冲文本,将该文本解码为字节,然后寻找(sys.stdin.read(1).decode();sys.stdin.seek(-1,io.SEEK_CUR).由于输入流中的不可编码字节而无法接受。使用peek从stdin的缓冲区中获取一些字节,将其切

Python 3.6 urllib 类型错误 : can't concat bytes to str

我正在尝试使用Python3.6中的urllib从API中提取一些JSON数据。它需要传递header信息以进行授权。这是我的代码:importurllib.request,jsonheaders={"authorization":"Bearer{authorization_token}"}withurllib.request.urlopen("{api_url}",data=headers)asurl:data=json.loads(url.read().decode())print(data)我得到的错误信息是:Traceback(mostrecentcalllast):File"

python - 尝试恢复检查点时 Tensorflow 失败并显示 "Unable to get element from the feed as bytes."

我正在使用Tensorflowr0.12。我在本地使用google-cloud-ml来运行2个不同的训练作业。在第一份工作中,我为我的变量找到了很好的初始值。我将它们存储在V2检查点中。当我尝试恢复我的变量以便在第二份工作中使用它们时:importtensorflowastfsess=tf.Session()new_saver=tf.train.import_meta_graph('../variables_pred/model.ckpt-10151.meta',clear_devices=True)new_saver.restore(sess,tf.train.latest_chec

python - TypeError : write() argument must be str, 不是字节(Python 3 与 Python 2)

下面的代码完美适用于python2.7.13importoswithopen('random.bin','w')asf:f.write(os.urandom(10))但是对于python3会抛出错误3.6.0|python4.3.0(64位)|(默认,2016年12月23日,11:57:41)[MSCv.190064位(AMD64)]Traceback(mostrecentcalllast):File"C:/Users/hsingh/PycharmProjects/Item3.py",line3,inf.write(os.urandom(10))TypeError:write()arg