Python writes a Python script

Source: Internet
Author: User

I want a program that can create backups for all of my important files. (The test environment below is python2.7)

1.backup_ver1.py

#!/usr/bin/pythonimport osimport time# 1. The files and directories to is backed up is specified in a list.source = ['/home/esun ']# If your is using Windows, use S Ource = [R ' C:\Documents ', R ' D:\Work '] or something like that# 2. The backup must stored in a main backup Directorytarget_dir = '/mnt/e/backup/' # Remember ll be using# 3. The files is backed up into a zip file.# 4. The name of the ZIP archive is the current date and Timetarget = Target_dir + time.strftime ('%y%m%d%h%m%s ') + '. Zip ' # 5. We Use the Zip command (in unix/linux) to put the files in a zip Archivezip_command = "Zip-qr '%s '%s"% (target, ". Joi  N (source)) # Run the backupif os.system (zip_command) = = 0:        print ' successful backup to ', Targetelse:        print ' backup FAILED '

The zip command has some options and parameters. The-Q option is used to indicate that the zip command works quietly. The-r option indicates that the ZIP command works recursively on the directory, that is, it includes subdirectories and files in subdirectories. Two options can be combined into an abbreviated form-QR. Option followed by the name of the ZIP archive you want to create, and then the list of files and directories to be backed up. We use the string join method we have learned to convert the source list to a string. Finally, we use the Os.system function to run the command, using the function as if it were running the command in the system. That is, run the command in the shell--if the command runs successfully, it returns 0, otherwise it returns the error number.

2.backup_ver2.py

#!/usr/bin/python# Filename:backup_ver2.pyimport osimport time# 1. The files and directories to is backed up is specified in a list.source = ['/home/esun ']# If your is using Windows, use S Ource = [R ' C:\Documents ', R ' D:\Work '] or something like that# 2. The backup must stored in a main backup Directorytarget_dir = '/mnt/e/backup/' # Remember ll be using# 3. The files is backed up into a zip file.# 4. The current day was the name of the subdirectory in the main directorytoday = Target_dir + time.strftime ('%y%m%d ') # The Cur  Rent time is the name of the zip Archivenow = time.strftime ('%h%m%s ') # Create the subdirectory if it isn ' t already thereif Not os.path.exists (today): Os.mkdir (today) # Make directory print ' successfully created directory ', today# The name of the zip Filetarget = today + os.sep + now + '. Zip ' # 5. We Use the Zip command (in unix/linux) to put the files in a zip Archivezip_command = "Zip-qr '%s '%s"% (target, ". Joi N (source) # Run the backupif os.system (zip_command) = = 0:print ' successful backup to ', Targetelse:print ' backup F AILED '

Most of the two programs are the same. The main change is to use the Os.exists function to verify if there are any in the primary backup directory. A directory with the current date as its name. If not, we use the Os.mkdir function to create the. Note the use of the OS.SEP variable-this will give you a directory delimiter based on your operating system, that is, under Linux, Unix it is '/', under Windows it is ' \ \ ', and in Mac OS it is ': '. Using os.sep rather than using characters directly will make our programs portable and work under these systems.

3. backup_ver4.py

#!/usr/bin/python# Filename:backup_ver4.pyimport osimport time# 1. The files and directories to is backed up is specified in a list.source = ['/home/esun ', '/etc ']# If you are using Window s, use Source = [R ' C:\Documents ', R ' D:\Work ') or something like that# 2. The backup must stored in a main backup Directorytarget_dir = '/mnt/e/backup/' # Remember ll be using# 3. The files is backed up into a zip file.# 4. The current day was the name of the subdirectory in the main directorytoday = Target_dir + time.strftime ('%y%m%d ') # The Cur Rent time is the name of the "the Zip Archivenow = time.strftime ('%h%m%s ') # Take a comment from the user to create the name of The zip filecomment = raw_input (' Enter a Comment-') if Len (comment) = = 0: # Check if a comment was entered TA  Rget = today + os.sep + now + '. zip ' Else:target = today + os.sep + Now + ' _ ' + comment.replace (', ' _ ') + '. Zip ' # Notice the backslash!# Create the subdirectory if it isn ' t alreadY Thereif 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 Archivezip_command = "Zip-qr '%s '%s"% (target, ". Joi N (source)) # Run the backupif os.system (zip_command) = = 0:print ' successful backup to ', Targetelse:print ' B Ackup FAILED '

We use the Raw_input function to get the user's comments and then find the length of the input through the Len function to verify that the user actually entered something. If the user just presses a carriage return (for example, it's just a routine backup and doesn't make any special modifications), then we'll proceed as before.

4. Summary: For most users, the fourth version is a satisfactory work script, but it still has room for further improvement. For example, you can include the degree of interactivity in your program-you can use the-V option to make your program more interactive. I also want an optimization that uses the TAR command instead of the zip command. such as: tar = ' tar-cvzf%s%s-x/home/swaroop/excludes.txt '% (target, '. Join (Srcdir)). The ideal way to create these archives is to use ZipFile and Tarfile, respectively. They are part of the Python standard library and are available for you to use. The use of these libraries avoids the use of os.system, a deprecated function, which can easily cause serious errors.

Python writes a Python script

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.