Python临时文件:坏了还是我做错了?

Python临时文件:坏了还是我做错了?,python,temporary-files,Python,Temporary Files,对于一个小的python脚本,我想在tempfile模块中使用一个临时文件。不知何故,它没有给出预期的行为,我不知道我做错了什么,或者这是否是一个bug: Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> impor

对于一个小的python脚本,我想在tempfile模块中使用一个临时文件。不知何故,它没有给出预期的行为,我不知道我做错了什么,或者这是否是一个bug:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> tmp = tempfile.TemporaryFile()
>>> tmp.read()
''
>>> tmp.write('test')
>>> tmp.read()
'P\xf6D\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ [ommitted]'
或者,我只尝试了文本模式,但行为仍然很奇怪:

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> tmp = tempfile.TemporaryFile('w+t')
>>> tmp.read()
''
>>> tmp.write('test')
>>> tmp.read()
'\x00\xa5\x8b\x02int or long, hash(a) is used instead.\n    i\x10 [ommitted]'
>>> tmp.seek(0)
>>> tmp.readline()
'test\x00\xa5\x8b\x02int or long, hash(a) is used instead.\n'
感谢您的帮助


其他信息:来自当前运行在Windows7 Enterprise x64计算机上的Python XY发行版的Python 2.7.2(32位)。在一次测试运行中,python在我的临时目录D:\temp\myusername下创建了临时文件名“tmpvyocxj”,并运行了其他几个python进程。对于输入的命令,我没有尝试在脚本中复制它。在没有其他python进程运行的情况下,该行为保持不变


更新:
此行为不仅限于tempfile模块,也适用于普通的file.read()和file.write()操作。根据CPython的说法,这两个函数只调用底层libc fread()例程。在C标准中,没有中间搜索或刷新的先读后写的确切行为是未定义的,即每个实现都可能导致不同的结果。

无法在Ubuntu上使用python 2.7.1重现

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> tmp = tempfile.TemporaryFile('w+t')
>>> tmp.read()
''
>>> tmp.write('test')
>>> tmp.read()
''
>>> tmp.seek(0)
>>> tmp.readline()
'test'
>>> 

我刚刚在WindowsXP上的Python2.7.1中重现了这种行为

这似乎是一个错误,只有当您尝试读取而不首先查找时才会发生

即:

>>> tmp.write('test')
>>> tmp.seek(0)
>>> tmp.read()
'test'
vs

编辑:

对于踢腿,我还检查了:

  • Windows 7,同样是2.7.1(与我的XP安装版本相同),并且在XP上看到了相同的行为
  • Cygwin版本2.6.5,并且此错误不存在

  • 您的代码在64位Ubuntu上使用Python2.6.5运行良好,因此问题可能是特定于平台的。无法在Windows7上重现。您可能需要提供更多信息-操作系统、临时文件的位置、您的环境的任何异常情况,等等。无法在Cygwin Python 2.6.4、Cygwin Python 3.1.2或Ubuntu Python 2.7.1+上复制。感谢您的测试和对该问题的确认。我向python人员提交了一份bug报告。这不是一个太大的问题,但因为它可能会泄漏信息,所以它肯定应该得到修复。
    >>> tmp.write('test')
    >>> tmp.read()
    'x\x01\x98\x00pfile.pyR\x05\x00\x00\x00G\x01\x00\x00s\x12 [blah blah blah]'
    >>> tmp.seek(0)
    >>> tmp.read()
    'testx\x01\x98\x00pfile.pyR\x05\x00\x00\x00G\x01\x00\x00s\x12 [blah blah blah]'