打开已经打开的文件不会引发异常

发布于 2021-01-29 14:55:56

考虑这两个python程序:

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_b.py如果当前通过打开文件,则会输出一个空字符串script_a.py

我期望IOError会引发异常,告诉我该文件已经打开,但是没有发生,而是文件看起来是空的。为什么会这样?检查它是否已被另一个进程打开的正确方法是什么?可以简单地检查是否返回了空字符串,然后重试直到读取其他内容,或者还有其他更Python化的方法吗?

关注者
0
被浏览
95
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    有关在Python中如何打开多个文件的信息,请参见其他答案和注释。如果已阅读所有内容,但仍想锁定对POSIX平台上文件的访问,则可以使用fcntl库。

    请记住:A)其他程序可能会忽略您对文件的锁定,B)一些联网的文件系统不能很好地实现锁定,或者根本没有实现C)请务必非常小心地释放锁定并避免死锁成群不会检测到它[1]

    [2]

    例子.... 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

    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
    

    希望这可以帮助!



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看