溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python10.4備份腳本的代碼怎么寫

發(fā)布時間:2021-10-26 15:47:44 來源:億速云 閱讀:146 作者:柒染 欄目:編程語言

python10.4備份腳本的代碼怎么寫,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

版本四的代碼是相當長的,所以很多人對其有束手無策之感,但是你通過以下的代碼對其,有更好的了解,以下就是相關內(nèi)容的詳細介紹。希望你會有所收獲。

  1. #!/usr/bin/python  

  2. # Filename: backup_ver4.py  

  3. import os  

  4. import time  

  5. # 1. The files and directories to be backed up are 
    specified in a list.  

  6. source = [‘/home/swaroop/byte’, ‘/home/swaroop/bin’]  

  7. # If you are using Windows, use source =
     [r'C:\Documents'
    , r'D:\Work'] or something like that  

  8. # 2. The backup must be stored in a main backup
     directory  

  9. target_dir = ‘/mnt/e/backup/’ # Remember to change 
    this to what you will be using  

  10. # 3. The files are backed up into a zip file.  

  11. # 4. The current day is the name of the 
    subdirectory in the main directory  

  12. today = target_dir + time.strftime(‘%Y%m%d’)  

  13. # The current time is the name of the zip archive  

  14. now = time.strftime(‘%H%M%S’)  

  15. # Take a comment from the user to create the name 
    of the zip file  

  16. comment = raw_input(‘Enter a comment –> ‘)  

  17. if len(comment) == 0: # check if a comment was entered  

  18. target = today + os.sep + now + ‘.zip’  

  19. else:  

  20. target = today + os.sep + now + ‘_’ + \  

  21. comment.replace(‘ ‘, ‘_’) + ‘.zip’  

  22. # Notice the backslash!  

  23. # Create the subdirectory if it isn’t already there  

  24. if not os.path.exists(today):  

  25. os.mkdir(today) # make directory  

  26. print ‘Successfully created directory’, today  

  27. # 5. We use the zip command (in Unix/Linux) to put the 
    files in a zip archive  

  28. zip_command = "zip -qr ‘%s’ %s" % (target, ‘ 
    ‘.join(source))  

  29. # Run the backup  

  30. if os.system(zip_command) == 0:  

  31. print ‘Successful backup to’, target  

  32. else:  

  33. print ‘Backup FAILED’ 

文中提到“我還希望有的一個優(yōu)化是使用tar命令替代zip命令。這樣做的一個優(yōu)勢是在你結合使用tar和gzip命令的時候,備份會更快更小。如果你想要在Windows中使用這些歸檔,WinZip也能方便地處理這些.tar.gz文件。tar命令在大多數(shù)Linux/Unix系統(tǒng)中都是默認可用的。Windows用戶也可以下載安裝它。命令字符串現(xiàn)在將成為:

  1. tar = ‘tar -cvzf %s %s -X /home/swaroop/
    excludes.txt’ % (target, ‘ ‘.join(srcdir)) 

需要補充的是Windows用戶安裝完LibArchive后命令為bsdtar,而且若想使用-z這個選項,還需安裝gzip軟件。代碼中的

target = today + os.sep + now + ‘.zip’

改為

target = today + os.sep + now + ‘.tar.gz’

使用

  1. bsdtar -cvzf %s %s -X /home/swaroop/
    excludes.txt’ % (target, ‘ ‘.join(source)) 

關于python10.4備份腳本的代碼怎么寫問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業(yè)資訊頻道了解更多相關知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI