#!/usr/bin/python
# Filename: backup_ver3.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['/home/swaroop/byte', '/home/swaroop/bin']
# If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that
# 2. The backup must be stored in a main backup directory
target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
# 3. The files are backed up into a zip file.
# 4. The current day is the name of the subdirectory in the main directory
today = target_dir + time.strftime('%Y%m%d')
# The current time is the name of the zip archive
now = time.strftime('%H%M%S')
# Take a comment from the user to create the name of the zip file
comment = raw_input('Enter a comment --> ')
if len(comment) == 0: # check if a comment was entered
target = today + os.sep + now + '.zip'
else:
target = today + os.sep + now + '_' +
comment.replace(' ', '_') + '.zip'
# Create the subdirectory if it isn't already there
if not os.path.exists(today):
os.mkdir(today) # make directory
print 'Successfully created directory', today
# 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
(源文件:code/backup_ver3.py)
輸出
$ python backup_ver3.py
File "backup_ver3.py", line 25
target = today + os.sep + now + '_' +
^
SyntaxError: invalid syntax
它如何(不)工作
這個程序不工作!Python 說有一個語法錯誤,這意味著腳本不滿足 Python 可以識別的結(jié)構(gòu)。當(dāng)我們觀察 Python 給出的錯誤的時候,它也告訴了我們它檢測出錯誤的位置。所以我們從那行開始 調(diào)試 我們的程序。
通過仔細(xì)的觀察,我們發(fā)現(xiàn)一個邏輯行被分成了兩個物理行,但是我們并沒有指明這兩個物理行屬于同一邏輯行?;旧希琍ython 發(fā)現(xiàn)加法操作符(+)在那一邏輯行沒有任何操作數(shù),因此它不知道該如何繼續(xù)。記住我們可以使用物理行尾的反斜杠來表示邏輯行在下一物理行繼續(xù)。所以,我們修正了程序。這被稱為修訂。