我正在寻找看门狗,但我发现this很好的库。如果在文件夹中创建文件,则需要适合DBSCAN模型。 Joblib用于scikit-learn的DBSCAN实现中,如果DBSCAN运行代码不在主线程中,则joblib不允许使用多处理。如果使用看门狗,则DBSCAN代码无法在主线程中运行。我该如何解决这个问题?您可以在下面找到看门狗脚本和一个简单的函数对其进行测试。当我运行main_watchdog.py
并将文件添加到看门狗正在监视的文件夹中时,它将运行Thread-1中的simple_function.py
。同时,main_watchdog.py
在MainThread中运行。
PS:解决方案每次调用simple_function.py
时可能会启动一个子进程,但如果在看门狗文件夹中创建了多个文件,恐怕这可能会引起一些问题。想象一下一次接收10或100或10000个文件...
#main_watchdog.py
import time
import logging
import threading
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from a_function import simple_function
class Event(LoggingEventHandler):
def on_created(self, event):
simple_function(x)
def on_modified(self, event):
simple_function(x)
if __name__ == "__main__":
x = 1
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# path = sys.argv[1] if len(sys.argv) > 1 else '.'
path = '/path/to/watch/the/folder'
event_handler = Event()
observer = Observer()
observer.schedule(event_handler, path, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
print(threading.current_thread().name)
except KeyboardInterrupt:
observer.stop()
observer.join()
#a_function.py
import threading
def simple_function(x):
x += 1
print(threading.current_thread().name)
print(x)
如果我要正确理解此问题,则需要业务逻辑在主线程中运行,而观察者在后台线程中运行。通过使用线程库在背景中调用观察者线程,然后通过Queues
将这些事件的值传递给函数调用,可以轻松解决此问题,这是线程之间的通信方式。