需要Python RSYNC脚本的反馈
这个脚本似乎工作得很好,但我相信你们中的一些大师可以对此进行优化 脚本的目的:需要Python RSYNC脚本的反馈,python,rsync,Python,Rsync,这个脚本似乎工作得很好,但我相信你们中的一些大师可以对此进行优化 脚本的目的: “监视”具有特定文件扩展名的新文件的目录 确保文件未被复制 将文件rsync到远程服务器 rsync删除该文件 脚本永远不停地循环 在互联网/网络中断情况下生存 在远程服务器上不保留部分文件 import os import subprocess import time import logging import datetime from sys import argv if len(argv) < 3:
- “监视”具有特定文件扩展名的新文件的目录
- 确保文件未被复制
- 将文件rsync到远程服务器
- rsync删除该文件
- 脚本永远不停地循环
- 在互联网/网络中断情况下生存
- 在远程服务器上不保留部分文件
import os import subprocess import time import logging import datetime from sys import argv if len(argv) < 3: exit('Please provide two arguments - Source Destination') LOC_DIR = argv[1] REM_DIR = argv[2] POLL_INT = 10 RUN_INT = 60 FILE_EXT = '.mov' # logging setup logging.basicConfig(filename='%s' % os.path.join(LOC_DIR, '%s script.log' % datetime.datetime.now()),level=logging.DEBUG) # make an easy print and logging function def printLog(string): print '%s %s' % (datetime.datetime.now(), string) logging.info('%s %s' % (datetime.datetime.now(), string)) # get the files with absolute paths def getFiles(path): return [os.path.join(path, entry) for entry in os.listdir(path)] # check if file is still being copied (file size has changed within the poll interval) def checkSize(path): same = False while same is False: printLog("Processing '%s'" % os.path.basename(path)) printLog('Waiting %s seconds for any filesize change' % POLL_INT) size1 = os.path.getsize(path) time.sleep(POLL_INT) size2 = os.path.getsize(path) if size1 == size2: same = True printLog('File size stayed the same for %s seconds' % POLL_INT) return same else: printLog('File size change detected. Waiting a further %s seconds' % POLL_INT) # check if correct file extension def checkExt(path): if path.endswith(FILE_EXT): return True # rsync subprocess def rsyncFile(path): printLog("Syncing file '%s'" % os.path.basename(path)) try: command = ['rsync', '-a', '--remove-source-files', path, REM_DIR] p = subprocess.Popen(command, stdout=subprocess.PIPE) for line in p.stdout: printLog("rsync: '%s'" %line) p.wait() if p.returncode == 0: printLog('<<< File synced successfully :) >>>') elif p.returncode == 10: printLog('****** Please check your internet connection!! ****** Rsync error code: %s' % p.returncode) else: printLog('There was a problem. Error code: %s' % p.returncode) except Exception as e: logging.debug(e) # main logic def main(): all_files = getFiles(LOC_DIR) files = [] for f in all_files: if checkExt(f): files.append(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') main() if __name__ == "__main__": main()
导入操作系统 导入子流程 导入时间 导入日志记录 导入日期时间 从系统导入argv 如果len(argv)<3: 退出('请提供两个参数-源-目标') LOC_DIR=argv[1] REM_DIR=argv[2] POLL_INT=10 RUN_INT=60 文件_EXT='.mov' #日志设置 logging.basicConfig(文件名=“%s”%os.path.join(LOC_DIR,“%s script.log”%datetime.datetime.now()),级别=logging.DEBUG) #制作一个简单的打印和记录功能 def打印日志(字符串): 打印“%s%s%”(datetime.datetime.now(),字符串) logging.info(“%s%s%”(datetime.datetime.now(),字符串)) #获取具有绝对路径的文件 def getFiles(路径): 对于os.listdir(路径)中的条目,返回[os.path.join(路径,条目)] #检查是否仍在复制文件(文件大小在轮询间隔内已更改) def checkSize(路径): 相同=错误 虽然这是错误的: 打印日志(“正在处理'%s'%os.path.basename(路径)) printLog('等待%s秒进行任何文件大小更改'%POLL\u INT〕 size1=os.path.getsize(路径) 睡眠时间(轮询时间) size2=os.path.getsize(路径) 如果size1==size2: 相同=正确 printLog('文件大小保持不变达%s秒'%POLL\u INT) 返回相同的 其他: printLog('检测到文件大小更改。请再等待%s秒'%POLL\u INT) #检查文件扩展名是否正确 def checkExt(路径): 如果路径.endswith(文件名): 返回真值 #rsync子进程 def rsyncFile(路径): 打印日志(“同步文件“%s””%os.path.basename(路径)) 尝试: 命令=['rsync','-a','-remove source files',path,REM_DIR] p=subprocess.Popen(命令,stdout=subprocess.PIPE) 对于p.stdout中的行: 打印日志(“rsync:'%s'”行) p、 等等 如果p.returncode==0: 打印日志(“>”) elif p.returncode==10: 打印日志('******请检查您的internet连接!!****Rsync错误代码:%s'%p.returncode) 其他: printLog('出现问题。错误代码:%s'%p.returncode) 例外情况除外,如e: logging.debug(e) #主要逻辑 def main(): 所有文件=获取文件(LOC\U DIR) 文件=[] 对于所有_文件中的f: 如果选中Ext(f): 文件。追加(f) 如果len(files)==1: 打印日志('>'%len(文件)) elif len(文件)>1: 打印日志('>'%len(文件)) 对于文件中的f: 如果检查大小(f): rsyncFile(f) printLog('未找到任何文件。请在%s秒内再次检查'%RUN\u INT!') 时间。睡眠(RUN_INT) printLog('检查文件') main() 如果名称=“\uuuuu main\uuuuuuuu”: main()
# check if correct file extension
def checkExt(path):
return path.endswith(FILE_EXT)
那就更像蟒蛇了
# 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")
#rsync子进程
def rsyncFile(路径):
打印日志(“同步文件“%s””%os.path.basename(路径))
尝试:
p=subprocess.Popen(['rsync','-a','-remove source files',path,REM_DIR],stdout=subprocess.PIPE)
对于p.stdout中的行:
打印日志(“rsync:'%s'”行)
p、 等等
打印日志(
{
0 : '>',
10:“******请检查您的internet连接!!****Rsync错误代码:%s”%p.returncode,
}.get(p.returncode,******请检查您的internet连接!!****Rsync错误代码:%s'%p.returncode)#python中的switch语句!
)
除:
logging.exception(“发生异常”)
使用“logging.exception”时,您将显示导致问题的异常和回溯
然后减少主管道压力
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')
def main():
尽管如此:
files=[f表示getFiles(LOC_DIR)中的f,如果选中ext(f)]
如果len(files)==1:
打印日志('>'%len(文件))
elif len(文件)>1:
打印日志('>'%len(文件))
对于文件中的f:
如果检查大小(f):
rsyncFile(f)
printLog('未找到任何文件。请在%s秒内再次检查'%RUN\u INT!')
时间。睡眠(RUN_INT)
printLog('检查文件')
“while True:”语句将避免在主代码末尾调用main()时容易达到的递归限制
欢迎评论:)Cedric,感谢您的反馈。。我从你的帖子中学到了很多。干杯MFB