Python 如何查看文件的更改?
我有一个日志文件正在由另一个进程编写,我希望监视它的更改。每次发生更改时,我都希望读入新数据,对其进行一些处理 最好的方法是什么?我希望PyWin32库中会有某种钩子。我找到了Python 如何查看文件的更改?,python,file,pywin32,watch,Python,File,Pywin32,Watch,我有一个日志文件正在由另一个进程编写,我希望监视它的更改。每次发生更改时,我都希望读入新数据,对其进行一些处理 最好的方法是什么?我希望PyWin32库中会有某种钩子。我找到了win32file.FindNextChangeNotification函数,但不知道如何要求它查看特定的文件 如果有人做过这样的事,我真的很高兴听到 [Edit]我应该提到我正在寻找一个不需要轮询的解决方案 [编辑]诅咒!这在映射的网络驱动器上似乎不起作用。我猜windows不会像在本地磁盘上那样“听到”文件的任何更新。
win32file.FindNextChangeNotification
函数,但不知道如何要求它查看特定的文件
如果有人做过这样的事,我真的很高兴听到
[Edit]我应该提到我正在寻找一个不需要轮询的解决方案
[编辑]诅咒!这在映射的网络驱动器上似乎不起作用。我猜windows不会像在本地磁盘上那样“听到”文件的任何更新。我不知道windows的任何特定功能。您可以尝试每隔一秒/分钟/小时获取文件的MD5哈希值(取决于您需要它的速度),并将其与上一个哈希值进行比较。当它不同时,您知道文件已更改,并读取最新的行。我会尝试类似的方法
try:
f = open(filePath)
except IOError:
print "No such file: %s" % filePath
raw_input("Press Enter to close window")
try:
lines = f.readlines()
while True:
line = f.readline()
try:
if not line:
time.sleep(1)
else:
functionThatAnalisesTheLine(line)
except Exception, e:
# handle the exception somehow (for example, log the trace) and raise the same exception again
raw_input("Press Enter to close window")
raise e
finally:
f.close()
循环检查自上次读取文件以来是否有新行-如果有,则读取并传递给分析该行的函数。否则,脚本将等待1秒并重试该过程 检查到a。您可以在Python中尝试相同的循环。建议:
import time
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
print line, # already has newline
另请参见问题。您是否已经查看了上提供的文档?如果您只需要它在Windows下工作,那么第二个示例似乎正是您想要的(如果您将目录路径与您想要查看的文件之一交换)
否则,轮询可能是唯一真正独立于平台的选项
注意:我还没有尝试过这些解决方案。如果轮询对您来说足够好,我只想看看“修改的时间”文件统计是否发生变化。阅读:
os.stat(filename).st_mtime
(还请注意,Windows本机更改事件解决方案并非在所有情况下都有效,例如在网络驱动器上。)
正如您在中所看到的,由指出,WIN32相对复杂,它监视目录,而不是单个文件
我建议您研究一下,这是一个.NET python实现。
使用IronPython,您可以使用所有.NET功能,包括
System.IO.FileSystemWatcher
它通过一个简单的事件接口处理单个文件。好吧,因为您使用的是Python,所以您只需打开一个文件并不断从中读取行即可
f = open('file.log')
如果读取的行不是空的,则进行处理
line = f.readline()
if line:
// Do what you want with the line
您可能不知道在EOF继续调用readline
是可以的。在这种情况下,它将继续返回一个空字符串。当日志文件中附加了某些内容时,将根据需要从停止的位置继续读取
如果您正在寻找使用事件或特定库的解决方案,请在问题中指定。否则,我认为这个解决方案很好。在对Tim Golden的脚本进行了一些黑客攻击之后,我有以下几点似乎非常有效:
import os
import win32file
import win32con
path_to_watch = "." # look at the current directory
file_to_watch = "test.txt" # look for changes to a file called test.txt
def ProcessNewData( newData ):
print "Text added: %s"%newData
# Set up the bits we'll need for output
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile (
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
# Open the file we're interested in
a = open(file_to_watch, "r")
# Throw away any exising log data
a.read()
# Wait for new data and call ProcessNewData for each new chunk that's written
while 1:
# Wait for a change to occur
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
None,
None
)
# For each change, check to see if it's updating the file we're interested in
for action, file in results:
full_filename = os.path.join (path_to_watch, file)
#print file, ACTIONS.get (action, "Unknown")
if file == file_to_watch:
newText = a.read()
if newText != "":
ProcessNewData( newText )
它可能需要进行更多的错误检查,但对于简单地查看日志文件并在将其输出到屏幕之前对其进行一些处理来说,这种方法效果很好
谢谢大家的意见-很棒的东西 它不应该在windows上工作(可能使用cygwin?),但是对于unix用户,应该使用“fcntl”系统调用。下面是一个Python示例。如果您需要用C(相同的函数名)编写代码,那么代码基本上是相同的
以下是Kender代码的简化版本,该代码似乎执行了相同的技巧,并且不会导入整个文件:
# Check file for new data.
import time
f = open(r'c:\temp\test.txt', 'r')
while True:
line = f.readline()
if not line:
time.sleep(1)
print 'Nothing New'
else:
print 'Call Function: ', line
退房
inotify在较新的linuxes中取代了dnotify(来自前面的答案),并允许文件级而非目录级监视。您尝试使用了吗
用于监视文件系统事件的Python API库和shell实用程序
使用
- 一个跨平台的API
- 用于运行命令以响应目录更改的shell工具
请快速开始使用中的一个简单示例
如果需要多平台解决方案,请选中。
下面是一个示例代码(未消毒):
这是Tim Goldan脚本的另一个修改,该脚本在unix类型上运行,并通过使用dict(file=>time)为文件修改添加了一个简单的监视程序
用法:whateverName.py path_to_dir_to_watch
#!/usr/bin/env python
import os, sys, time
def files_to_timestamp(path):
files = [os.path.join(path, f) for f in os.listdir(path)]
return dict ([(f, os.path.getmtime(f)) for f in files])
if __name__ == "__main__":
path_to_watch = sys.argv[1]
print('Watching {}..'.format(path_to_watch))
before = files_to_timestamp(path_to_watch)
while 1:
time.sleep (2)
after = files_to_timestamp(path_to_watch)
added = [f for f in after.keys() if not f in before.keys()]
removed = [f for f in before.keys() if not f in after.keys()]
modified = []
for f in before.keys():
if not f in removed:
if os.path.getmtime(f) != before.get(f):
modified.append(f)
if added: print('Added: {}'.format(', '.join(added)))
if removed: print('Removed: {}'.format(', '.join(removed)))
if modified: print('Modified: {}'.format(', '.join(modified)))
before = after
这是一个检查文件更改的示例。这可能不是最好的方法,但肯定是一条捷径
当对源代码进行更改时,用于重新启动应用程序的便捷工具。我在玩pygame时做了这个,所以我可以看到效果在文件保存后立即发生
当在pygame中使用时,确保“while”循环中的内容放在游戏循环中,即更新或其他任何内容。否则,您的应用程序将陷入无限循环,您将无法看到游戏更新
file_size_stored = os.stat('neuron.py').st_size
while True:
try:
file_size_current = os.stat('neuron.py').st_size
if file_size_stored != file_size_current:
restart_program()
except:
pass
以防你想要我在网上找到的重启代码。给你。(与该问题无关,尽管它可能会派上用场)
让电子做你们想让它们做的事情,享受其中的乐趣。对我来说,最简单的解决方案就是使用watchdog的工具watchmedo
从现在起,我有了一个在目录中查找sql文件并在必要时执行它们的进程
watchmedo shell-command \
--patterns="*.sql" \
--recursive \
--command='~/Desktop/load_files_into_mysql_database.sh' \
.
下面是一个用于查看每秒写入不超过一行但通常很少的输入文件的示例。目标是将最后一行(最近写入)附加到指定的输出文件。我从我的一个项目中复制了这个,只是删除了所有不相关的行。您必须填写或更改缺少的符号
from PyQt5.QtCore import QFileSystemWatcher, QSettings, QThread
from ui_main_window import Ui_MainWindow # Qt Creator gen'd
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
Ui_MainWindow.__init__(self)
self._fileWatcher = QFileSystemWatcher()
self._fileWatcher.fileChanged.connect(self.fileChanged)
def fileChanged(self, filepath):
QThread.msleep(300) # Reqd on some machines, give chance for write to complete
# ^^ About to test this, may need more sophisticated solution
with open(filepath) as file:
lastLine = list(file)[-1]
destPath = self._filemap[filepath]['dest file']
with open(destPath, 'a') as out_file: # a= append
out_file.writelines([lastLine])
当然,并不严格要求包含QMainWindow类,也就是说,您可以单独使用QFileSystemWatcher 最好、最简单的解决方案是使用pygtail:
观看
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
class myThread (threading.Thread):
def __init__(self, threadID, fileName, directory, origin):
threading.Thread.__init__(self)
self.threadID = threadID
self.fileName = fileName
self.daemon = True
self.dir = directory
self.originalFile = origin
def run(self):
startMonitor(self.fileName, self.dir, self.originalFile)
def startMonitor(fileMonitoring,dirPath,originalFile):
hDir = win32file.CreateFile (
dirPath,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
# Wait for new data and call ProcessNewData for each new chunk that's
# written
while 1:
# Wait for a change to occur
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
False,
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
None,
None
)
# For each change, check to see if it's updating the file we're
# interested in
for action, file_M in results:
full_filename = os.path.join (dirPath, file_M)
#print file, ACTIONS.get (action, "Unknown")
if len(full_filename) == len(fileMonitoring) and action == 3:
#copy to main file
...
file_size_stored = os.stat('neuron.py').st_size
while True:
try:
file_size_current = os.stat('neuron.py').st_size
if file_size_stored != file_size_current:
restart_program()
except:
pass
def restart_program(): #restart application
python = sys.executable
os.execl(python, python, * sys.argv)
watchmedo shell-command \
--patterns="*.sql" \
--recursive \
--command='~/Desktop/load_files_into_mysql_database.sh' \
.
from PyQt5.QtCore import QFileSystemWatcher, QSettings, QThread
from ui_main_window import Ui_MainWindow # Qt Creator gen'd
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
Ui_MainWindow.__init__(self)
self._fileWatcher = QFileSystemWatcher()
self._fileWatcher.fileChanged.connect(self.fileChanged)
def fileChanged(self, filepath):
QThread.msleep(300) # Reqd on some machines, give chance for write to complete
# ^^ About to test this, may need more sophisticated solution
with open(filepath) as file:
lastLine = list(file)[-1]
destPath = self._filemap[filepath]['dest file']
with open(destPath, 'a') as out_file: # a= append
out_file.writelines([lastLine])
from pygtail import Pygtail
import sys
while True:
for line in Pygtail("some.log"):
sys.stdout.write(line)
import os
import sys
import time
class Watcher(object):
running = True
refresh_delay_secs = 1
# Constructor
def __init__(self, watch_file, call_func_on_change=None, *args, **kwargs):
self._cached_stamp = 0
self.filename = watch_file
self.call_func_on_change = call_func_on_change
self.args = args
self.kwargs = kwargs
# Look for changes
def look(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
# File has changed, so do something...
print('File changed')
if self.call_func_on_change is not None:
self.call_func_on_change(*self.args, **self.kwargs)
# Keep watching in a loop
def watch(self):
while self.running:
try:
# Look for changes
time.sleep(self.refresh_delay_secs)
self.look()
except KeyboardInterrupt:
print('\nDone')
break
except FileNotFoundError:
# Action on file not found
pass
except:
print('Unhandled error: %s' % sys.exc_info()[0])
# Call this function each time a change happens
def custom_action(text):
print(text)
watch_file = 'my_file.txt'
# watcher = Watcher(watch_file) # simple
watcher = Watcher(watch_file, custom_action, text='yes, changed') # also call custom action function
watcher.watch() # start the watch going
repyt ./app.py
import os
import sys
import time
class Watcher(object):
running = True
refresh_delay_secs = 1
# Constructor
def __init__(self, watch_files, call_func_on_change=None, *args, **kwargs):
self._cached_stamp = 0
self._cached_stamp_files = {}
self.filenames = watch_files
self.call_func_on_change = call_func_on_change
self.args = args
self.kwargs = kwargs
# Look for changes
def look(self):
for file in self.filenames:
stamp = os.stat(file).st_mtime
if not file in self._cached_stamp_files:
self._cached_stamp_files[file] = 0
if stamp != self._cached_stamp_files[file]:
self._cached_stamp_files[file] = stamp
# File has changed, so do something...
file_to_read = open(file, 'r')
value = file_to_read.read()
print("value from file", value)
file_to_read.seek(0)
if self.call_func_on_change is not None:
self.call_func_on_change(*self.args, **self.kwargs)
# Keep watching in a loop
def watch(self):
while self.running:
try:
# Look for changes
time.sleep(self.refresh_delay_secs)
self.look()
except KeyboardInterrupt:
print('\nDone')
break
except FileNotFoundError:
# Action on file not found
pass
except Exception as e:
print(e)
print('Unhandled error: %s' % sys.exc_info()[0])
# Call this function each time a change happens
def custom_action(text):
print(text)
# pass
watch_files = ['/Users/mexekanez/my_file.txt', '/Users/mexekanez/my_file1.txt']
# watcher = Watcher(watch_file) # simple
if __name__ == "__main__":
watcher = Watcher(watch_files, custom_action, text='yes, changed') # also call custom action function
watcher.watch() # start the watch going
@echo off
:top
xcopy /m /y %1 %2 | find /v "File(s) copied"
timeout /T 1 > nul
goto :top
nodemon -w 'src/**' -e py,html --exec python src/app.py
import inotify.adapters
from datetime import datetime
LOG_FILE='/var/log/mysql/server_audit.log'
def main():
start_time = datetime.now()
while True:
i = inotify.adapters.Inotify()
i.add_watch(LOG_FILE)
for event in i.event_gen(yield_nones=False):
break
del i
with open(LOG_FILE, 'r') as f:
for line in f:
entry = line.split(',')
entry_time = datetime.strptime(entry[0],
'%Y%m%d %H:%M:%S')
if entry_time > start_time:
start_time = entry_time
print(entry)
if __name__ == '__main__':
main()