MFB
MFB

Reputation: 19817

Feedback on Python RSYNC script wanted

This script appears to work great, but I'm sure this could be optimised by some of you gurus!

Purpose of script:

Upvotes: 1

Views: 2041

Answers (1)

Cédric Julien
Cédric Julien

Reputation: 80811

first, eliminate useless statement

# check if correct file extension
def checkExt(path):
    return path.endswith(FILE_EXT)

then be a little more pythonic

# rsync subprocess
def rsyncFile(path):
    printLog("Syncing file '%s'" % os.path.basename(path))
    try:
        p = subprocess.Popen(['rsync', '-a', '--remove-source-files', path, REM_DIR], stdout=subprocess.PIPE)
        for line in p.stdout:
            printLog("rsync: '%s'" %line)
        p.wait()
        printlog(
            { 
                0  : '<<< File synced successfully :) >>>',
                10 : '****** Please check your internet connection!! ******  Rsync error code: %s' % p.returncode,
            }.get(p.returncode, '****** Please check your internet connection!! ******  Rsync error code: %s' % p.returncode) # A switch statement in python !
        )
    except:
        logging.exception("An exception occured")

When using "logging.exception" you will display the exception and traceback that caused the problem.

then reduce main

def main():
    while True:
        files = [f for f in getFiles(LOC_DIR) if checkExt(f)]
        if len(files) == 1:
            printLog('<<< Found %s matching file >>>' % len(files))
        elif len(files) > 1:
            printLog('<<< Found %s matching files >>>' % len(files))
        for f in files:
            if checkSize(f):
                rsyncFile(f)
        printLog('No files found.  Checking again in %s seconds' % RUN_INT)
        time.sleep(RUN_INT)
        printLog('Checking for files')

the "while True:" statement will avoid recursion limit you could easily reach when calling main() at the end of the main code

comments and remarks are welcome :)

Upvotes: 2

Related Questions