事件发生后如何触发python代码

时间:2019-05-28 15:02:20

标签: python

我想在另一个软件之后启动一些python代码。

该软件进行一些数据提取,并定期(每周一次)以CVS文件格式向我提供一些结果。我想做的是触发我的Python代码在这些文件上执行,以便对它们执行某些功能,我希望在每次提取后都执行此操作。

我尝试了while(1),但效率似乎不高。

是否有可用来解决此问题的Python代码或执行Python的软件?预先感谢。

1 个答案:

答案 0 :(得分:0)

您可以观看文件夹,然后执行文件创建和/或修改事件。如果需要,您的脚本可以监视网络上的远程驱动器。

以下内容已从有效代码中删除,但我无法确认它在此代码段状态下是否有效。新创建的文件将调用HandleNewlyCreated()

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class WatchPendingHandler(FileSystemEventHandler):
    ''' Run a handler for every file added to the pending dir

    This class also handles what I call a bug in the watchdog module
    which means that you can get more than one call per real event
    in the watched dir tree.
    '''

    def __init__(self):
        super(WatchPendingHandler, self).__init__()
        # wip is used to avoid bug in watchdog which means multiple calls
        # for one real event.
        # For reference: https://github.com/gorakhargosh/watchdog/issues/346
        self.wip = []

    def on_created(self, event):
        path = event.src_path
        if event.is_directory:
            logging.debug('WatchPendingHandler() New dir created in pending dir: {}'.format(path))
            return
        if path in self.wip:
            logging.debug('WatchPendingHandler() Dup created event for %s', path)
            return
        self.wip.append(path)
        logging.debug('WatchPendingHandler() New file created in pending dir: {}'.format(path))
        HandleNewlyCreated(path)

    def on_moved(self, event):
        logging.debug('WatchPendingHandler() %s has been moved', event.src_path)
        with contextlib.suppress(ValueError):
            self.wip.remove(event.src_path)

    def on_deleted(self, event):
        path = event.src_path
        logging.debug('WatchPendingHandler() %s has been deleted', path)
        with contextlib.suppress(ValueError):
            self.wip.remove(path)

observer = Observer()
observer.schedule(WatchPendingHandler(), DIR_PENDING, recursive=True)
observer.start()
logging.info('Watching %s', DIR_PENDING)
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

on_created()的解释: 它将检查该事件是否用于创建目录。如果是这样,它将记录该事件,然后返回/忽略它。然后,它检查先前是否已发生文件创建事件(self.wip中的路径)。如果是这样,它也会忽略该事件并返回。现在,它可以将事件记录在self.wip中,记录新事件,然后调用HandleNewlyCreated()处理新创建的文件。

如果文件被移动或删除,那么我们需要从self.wip中删除路径,以使下一个为新文件创建的事件不会被忽略。

此处有更多信息:https://pypi.org/project/watchdog/