Make this directory synchronization script detect the change and run in the background

I have this simple python script that will synchronize the contents of a folder sourcedirwith a folder targetdir.

Here is the code:

from dirsync import sync

sourcedir = "C:/sourcedir"
targetdir ="C:/targetdir"
sync(sourcedir, targetdir, "sync")

It is cumbersome to manually run this script every time you make changes. I would like this script to run in the background, so that whenever there are any changes to the folder sourcedir, the folder targetdirwill sync automatically.

I am using python v3.5

+4
source share
6 answers

Here's the library application for this:

import sys
import time
import logging
from watchdog.observers import Observer


def event_handler(*args, **kwargs):
    print(args, kwargs)


if __name__ == "__main__":
    path = '/tmp/fun'
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
+3
source

(, os.path.getmtime(sourcepath)) dir , .

import os
import time
from dirsync import sync

sourcedir = "C:/sourcedir"
targetdir ="C:/targetdir"

mtime, oldmtime = None, None

while True:
    mtime = os.path.getmtime(sourcedir)
    if mtime != oldmtime:
        sync(sourcedir, targetdir, "sync")
        oldmtime = mtime
    time.sleep(60)
+2

script linux, inotify. (GitHub).

, , - , , , .. , epoll .

import inotify.adapters

i = inotify.adapters.Inotify()
i.add_watch(b'/tmp')
try:
    for event in i.event_gen():
        if event is not None:
            (header, type_names, watch_path, filename) = event
            if 'IN_MODIFY' in type_names:
                # Do something
                sync(sourcedir, targetdir, "sync")
finally:
    i.remove_watch(b'/tmp')

, multiprocessing sync, script . sync , .

, , , .

+2

Windows watcher, Python API.NET FileSystemWatcher.

Linux inotifyx, Python API- Linux inoify.

+2

Source: https://habr.com/ru/post/1664133/


All Articles