我的申请,我有以下要求: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....
Run Code Online (Sandbox Code Playgroud)
那么,我如何检查文件是否已经打开或被其他进程使用?我在互联网上做了一些研究.并有一些结果:
try:
myfile = open(filename, "r+") # or "a+", whatever you need
except IOError:
print "Could not open file! Please close Excel!"
Run Code Online (Sandbox Code Playgroud)
我尝试了这段代码,但无论我使用"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
Run Code Online (Sandbox Code Playgroud)
此代码可以工作,但它无法达到我的请求,因为我不想删除该文件以检查它是否已打开.
python ×1