【问题标题】:Detecting broken stream in python when file is deleted删除文件时在python中检测损坏的流
【发布时间】:2011-08-22 17:56:10
【问题描述】:

我的问题是,当日志旋转时,python 程序的日志记录会停止。 我已将其追踪到流本身。我看不到任何方法来判断流是否从 python 中断。删除文件后,它仍然可以毫无问题地接受写入。

import os

FILE = 'testing.txt'

fs = open(FILE, 'a')
fs.write('word')
os.remove(FILE)
fs.write('Nothing....') # Nothing breaks
print(fs.errors) # No errors

那么,如何确定文件流是否仍然有效? 并且检查文件是否存在也无济于事,因为无论流是否仍然有效,文件都将始终存在。

【问题讨论】:

  • 你用的是什么操作系统和什么版本的python?我尝试运行它并且 os.remove(FILE) 给了我一个错误;它说文件正在使用中!我没有在任何其他程序中打开它,所以它一定是在 python 中打开的。我在这台笔记本电脑上使用 XP,因为它是我的学校电脑,它只有 Python 2.5
  • 有趣。我的目标操作系统是 Linux (redhat) 和 Python 2.6.5。我在 Linux (Ubuntu) Python 2.7.1 中测试了代码

标签: python linux stream delete-file logrotate


【解决方案1】:

经过更多检查,我找到了解决方案。这是一个操作系统特定的问题。当文件在 Linux(或 Macintosh)中被删除时,它只是取消链接。 (我不知道这一点) 所以如果你在机器上运行 lsof,它仍然会显示文件是打开的。

[user@machine]$ lsof | grep --color -i "testing.txt"
python26  26495    user    8w      REG               8,33     23474     671920 /home/user/temp/testing.txt (deleted)

解决方案是在python中统计流。

stat = os.fstat(fs.fileno())

这会给你它拥有的链接数量。

if stat.st_nlink < 1:
    #has been deleted

然后就可以了。现在您知道是否应该重新加载它。希望这对其他人有帮助。

【讨论】:

    【解决方案2】:

    试试Exception handling:

    import os
    
    FILE = 'testing.txt'
    
    try:
        fs = open(FILE, 'a')
        fs.write('word')
        os.remove(FILE)
        fs.write('Nothing....') # Nothing breaks
    except Exception, e:
        print "Error:", e
    print(fs.errors) # No errors
    

    【讨论】:

      【解决方案3】:

      如果您需要更多的智能,而不仅仅是try: except: 子句,则可以使用 ionotify 的 python 绑定。但我认为它只与 Linux 相关(我不确定你的平台)

      【讨论】:

        【解决方案4】:

        我发现的另一个解决方案是将“copytruncate”标志添加到 logrotate 配置中。 有关详细信息,请参阅“man logrotate”。

        【讨论】:

          猜你喜欢
          • 2019-08-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-11
          • 2021-07-30
          • 2013-06-04
          相关资源
          最近更新 更多