<p>通过使用<a href="https://github.com/gorakhargosh/watchdog" rel="nofollow">^{<cd2>}</a>和<code>grep</code>模块,您可以完全摆脱<code>tail -f</code>部分(尽管在本例中,您甚至不需要它,因为您的搜索条件可以编写为简单的成员资格测试)。你知道吗</p>
<p>下面是一个简单的示例(根据文档进行了修改),可以满足您的要求:</p>
<pre><code>import sys
import time
from watchdog.observers import Observer
from watchdog.handlers import FileSystemEventHandler
class WatchFiles(FileSystemEventHandler):
def process_file(self, event):
"""
does stuff the file
"""
with open(event.src_path, 'r') as f:
for line in f:
if 'pattern' in line:
do_stuff(line)
def on_modified(self, event):
self.process_file(event)
def on_created(self, event):
self.process_file(event)
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else '.'
observer = Observer()
observer.schedule(WatchFiles(), path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
</code></pre>
<p>这样,您的应用程序不仅更易于移植,而且其所有部分都是独立的。你知道吗</p>