5

以下 Python 3 代码在我运行时表现出一些奇怪的行为(至少对我而言)strace

import os
import sys

if len(sys.argv) != 2:
    print('Usage: ecpy <filename>')
sys.exit(1)
try:
    print('my PID: %d' % os.getpid())
    with open(sys.argv[1], 'w') as fp:
        try:
            fp.write('Hello Stack Overflow!')
        except IOError as e:
            print('### before close')
            print(str(e))
            sys.stdout.flush()
except IOError as e:
    print('### after close')
    print(str(e))
    sys.stdout.flush()

print('### after exception block')
sys.stdout.flush()

由于 I/O 是缓冲的,如果您使用 运行此代码/dev/full,它不会失败,直到在块fp末尾关闭。with这并不奇怪。在 Python 2.7.3rc2(在我的系统上)中,代码在实际关闭对应于的文件描述符后运行异常处理程序fp

write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
close(3)                                = 0
munmap(0x7f9de3f78000, 4096)            = 0
write(1, "### after close\n", 16)       = 16
write(1, "[Errno 28] No space left on devi"..., 35) = 35
write(1, "### after exception block\n", 26) = 26

但是,在 Python 3.2.3(在我的系统上)中,异常块运行后文件描述符仍然打开:

write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
write(1, "### after close\n", 16)       = 16
write(1, "[Errno 28] No space left on devi"..., 35) = 35
write(1, "### after exception block\n", 26) = 26
...
write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
write(3, "Hello Stack Overflow!", 21)   = -1 ENOSPC (No space left on device)
close(3)                                = 0

解释器尝试再写入文件几次,然后静默失败。Python 什么时候真正调用close()?什么在调用它?这种行为似乎泄漏了文件描述符。

4

1 回答 1

2

我冒昧地向 bugs.python.org 提交了一个问题,让我们拭目以待,看看它是否会成功。

http://bugs.python.org/issue16597

编辑:看起来这是一个错误,很好!

于 2012-12-02T23:31:39.650 回答