4

我的问题是,当日志旋转时,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

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

4

4 回答 4

2

Upon much more inspection, I found the solution. It is an OS specific problem. When the file is deleted in Linux (or Macintosh) it just unlinks it. (I was not aware of this) So if you run lsof on the machine, it still shows the file as open.

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

The solution is to stat the stream in python.

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

Which will give you the number of links it has.

if stat.st_nlink < 1:
    #has been deleted

And there you go. Now you know if you should reload it or not. Hopefully this helps someone else.

于 2011-05-11T13:41:20.120 回答
0

尝试异常处理

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
于 2011-05-10T19:18:48.153 回答
0

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

于 2011-05-10T19:28:20.807 回答
0

Another solution I found is to add the "copytruncate" flag into the logrotate config. See "man logrotate" for more info.

于 2011-08-15T14:01:47.160 回答