在我的应用程序中,我有以下要求:1.有一个线程将定期在文件中记录一些日志。日志文件将在一定间隔内翻转。用于保持日志文件较小。2.还有另一个线程将定期处理这些日志文件。例如:将日志文件移到其他位置,解析日志内容以生成一些日志报告。
但是,有一个条件是第二个线程无法处理用于记录日志的日志文件。在代码方面,伪代码类似如下:
#code in second thread to process the log files
for logFile in os.listdir(logFolder):
if not file_is_open(logFile) or file_is_use(logFile):
ProcessLogFile(logFile) # move log file to other place, and generate log report....
那么,如何检查文件是否已打开或被其他进程使用?我在互联网上做了一些研究。并得到一些结果:
try:
myfile = open(filename, "r+") # or "a+", whatever you need
except IOError:
print "Could not open file! Please close Excel!"
我尝试了此代码,但是无论我使用“ r +”还是“ a +”标志,该代码均无效
try:
os.remove(filename) # try to remove it directly
except OSError as e:
if e.errno == errno.ENOENT: # file doesn't exist
break
该代码可以工作,但是无法达到我的要求,因为我不想删除该文件以检查它是否打开。
杨魅力
不负相思意
相关分类