打开已打开的文件不会引发异常 [英] Opening already opened file does not raise exception

查看:188
本文介绍了打开已打开的文件不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这两个python程序:

Consider those two python programs:

script_a.py

from datetime import datetime
from time import sleep

while True:
    sleep(1)
    with open('foo.txt', 'w') as f:
        sleep(3)
        s = str(datetime.now())
        f.write(s)
        sleep(3)

script_b.py

while True:
    with open('foo.txt') as f:
        s = f.read()
        print s

运行 script_a.py 。在运行时,启动 script_b.py 。两者都会很高兴地运行,但如果文件当前由 script_a.py 打开,则 script_b.py 将输出一个空字符串。

Run script_a.py. While it is running, start script_b.py. Both will happily run, but script_b.py outputs an empty string if the file is currently opened by script_a.py.

我期待引发一个 IOError 异常,告诉我该文件已经打开,不会发生,而是文件看起来是空的。为什么会这样,检查是否被另一个进程打开的正确方法是什么?是否可以简单地检查一个空字符串是否返回,并重新尝试,直到其他东西被读取,还是有更多的pythonic方式?

I was expecting an IOError exception to be raised, telling me the file is already opened, but it didn't happen, instead the file looks empty. Why is that and what would be the proper way to check if it is opened by another process? Would it be ok to simply check if an empty string is returned and try again until something else is read, or is there a more pythonic way?

推荐答案

请参阅关于多个文件在Python中打开工作的其他答案和评论。如果您已经阅读了所有这些内容,并且仍然希望锁定POSIX平台上的文件访问权限,那么您可以使用 fcntl 库。

See the other answer and comments regarding how multiple file opens work in Python. If you've read all that, and still want to lock access to the file on a POSIX platform, then you can use the fcntl library.

请记住:A)其他程序可能会忽略您对该文件的锁定,B)某些联网文件系统不能很好地实现锁定,或者在所有C上)确保非常小心释放锁并避免死锁,因为flock不会检测到它 [1] [2]

Keep in mind that: A) other programs may ignore your lock on the file, B) some networked file systems don't implement locking very well, or at all C) be sure to be very careful to release locks and avoid deadlock as flock won't detect it [1][2].

示例....
script_a.py

Example.... script_a.py

from datetime import datetime
from time import sleep
import fcntl

while True:
    sleep(1)
    with open('foo.txt', 'w') as f:
        s = str(datetime.now())

        print datetime.now(), "Waiting for lock"
        fcntl.flock(f, fcntl.LOCK_EX)
        print datetime.now(), "Lock clear, writing"

        sleep(3)
        f.write(s)

        print datetime.now(), "releasing lock"
        fcntl.flock(f, fcntl.LOCK_UN)

script_b.py

script_b.py

import fcntl
from datetime import datetime

while True:
    with open('foo.txt') as f:
        print datetime.now(), "Getting lock"
        fcntl.flock(f, fcntl.LOCK_EX)
        print datetime.now(), "Got lock, reading file"

        s = f.read()

        print datetime.now(), "Read file, releasing lock"
        fcntl.flock(f, fcntl.LOCK_UN)

        print s

希望这有帮助!

这篇关于打开已打开的文件不会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆