Advertisement
Guest User

Shelve problems

a guest
Oct 23rd, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.06 KB | None | 0 0
  1. import os, shutil, shelve, time
  2.  
  3. #Backup.py
  4. #Backs shit up
  5.  
  6. def BackUpAll (path, bupath):
  7.  
  8.     #Gets the name from the original folder and makes a new one
  9.     names = os.path.split(path)
  10.     new_name = names[1]+' '+GetTime()
  11.     new_path = bupath + "\\" + new_name
  12.  
  13.     print("Copying files from %s to %s"%(path,new_path))
  14.     #shutil.copy(path,new_path)
  15.    
  16.  
  17. def CheckBUPath ():
  18.     """Gets a path from user and checks if it's empty.
  19.    If not, it asks the user if he wants to change it."""
  20.     create_path=True
  21.     while create_path:
  22.         #Creating Backup path
  23.         print("Where would you like to create your backup?")
  24.         path = MakePath()
  25.         os.chdir(path)
  26.  
  27.         #Checking if something already exists at that path
  28.         if len(os.listdir()) >= 1:
  29.             print("\nSomething already exists there: ")
  30.             resume = Walkpath(path,"Short")
  31.             print("%d folders and %d documents\n"%(resume[0],resume[1]))
  32.             print('Would you like to change your location?')
  33.             answer = YesNo()
  34.             if answer =="YES" or answer =="Y":
  35.                 continue
  36.             elif answer =="NO" or answer =="N":
  37.                 break
  38.         else:
  39.             print("The path is empty! Proceeding with setup...")
  40.  
  41.     return path
  42.  
  43.  
  44. def GetTime():
  45.     """Gets the time in a DD/MM/YY-HH/MM/SS format"""
  46.     date = time.strftime("%x")
  47.     hour = time.strftime("%X")
  48.     full_time  = date+'-'+hour
  49.     return full_time
  50.  
  51.  
  52. def MakePath ():
  53.     """Gets a valid path from user."""
  54.     while True:
  55.         path = input("Enter path here: ").strip(' ')
  56.         if not os.path.exists(path):
  57.             print("That path does not exist, please enter a valid path.")
  58.         else:
  59.             break
  60.     return path
  61.  
  62.  
  63. def Setup():
  64.     """Walks the user through setting a path location and other settings"""
  65.    
  66.     print("We will walk you around creating your backup and backup preferences\n")
  67.  
  68.     #Setting the directory to be backed up
  69.     print("What directory would you like to backup?")
  70.     path = MakePath()
  71.    
  72.     print("Would you like to se all folders and files at that path? (enter YES|NO)")
  73.     answer = YesNo()
  74.    
  75.     if answer =="YES" or answer =="Y":
  76.         Walkpath(path)
  77.     elif answer =="NO" or answer =="N":
  78.         print("\n")
  79.         print("Okay, let's proceed.")
  80.     else:
  81.         raise Exception ("Something went wrong with your answer")
  82.    
  83.     answer=""       #AnswerReset
  84.  
  85.     #Setting the backup directory
  86.     bupath = CheckBUPath()
  87.     print("Would you like to save this destination (%s) as your default backup location ?\
  88.    That way you don't have to type it again."%bupath)
  89.     answer = YesNo()
  90.    
  91.     if answer =="YES" or answer =="Y":
  92.         WorkShelf('BackUpPath','store', bupath)
  93.        
  94.     else:
  95.         print("Okay, let's proceed")
  96.        
  97.     answer = ""     #AnswerReset
  98.  
  99.     #Remembering files to be backed up location
  100.     print("\nIf you're going to be backing the same data up\
  101.    we can save the files location so you don't have to type all the paths again.")
  102.     print("Would you like me to remember the backup file's location?")
  103.     answer = YesNo()
  104.    
  105.     if answer =="YES" or answer =="Y":
  106.         WorkShelf('Path2BU', 'store', path)
  107.        
  108.     else:
  109.         print("Okay, let's proceed")
  110.        
  111.     answer = ""     #AnswerReset
  112.  
  113.  
  114.     return path, bupath
  115.  
  116.        
  117. def Walkpath (path, version = 'Long'):
  118.     """Walks a path and prints out all the contents with structure.
  119.    Also gives a short version with number of files and subfolders."""
  120.     walk = os.walk(path)
  121.    
  122.     #Long
  123.     if version == "Long":
  124.         for (CurrentDir, Subdirs, Docs) in walk:
  125.             print('___________\n')
  126.             print('CURRENT FOLDER: ',CurrentDir)
  127.            
  128.             if len(Subdirs) >= 1:
  129.                 print("This folder (%s) contains the following subfolders: "%CurrentDir)
  130.                 for subdir in Subdirs:
  131.                     print("\t-", subdir)
  132.             else:
  133.                 print("No subfolders found")
  134.  
  135.             if len(Docs) >= 1:
  136.                 print("This folder (%s) contains the following documents: "%CurrentDir)
  137.                 for doc in Docs:
  138.                     print("\t-", doc)
  139.             else:
  140.                 print("No documents found")
  141.         print('\n'*4)
  142.  
  143.     #Short
  144.     elif version == "Short":
  145.         nb_subs, nb_docs = 0,0
  146.         for (CurrentDir, Subdirs, Docs) in walk:
  147.             for subdir in Subdirs:
  148.                 nb_subs += 1
  149.             for doc in Docs:
  150.                 nb_docs += 1
  151.        
  152.         resume = [nb_subs, nb_docs]
  153.         return resume
  154.  
  155.     else:
  156.         raise Exception ('Error in Backup.Walkpath')
  157.  
  158.  
  159. def WorkShelf(key, mode='get', variable=None):
  160.     """Either stores a variable to the shelf or gets one from it.
  161.    Possible modes are 'store' and 'get'"""
  162.     config = shelve.open('Config')
  163.    
  164.     if mode.strip() == 'get':
  165.         print(config[key])
  166.         return config[key]
  167.    
  168.     elif mode.strip() == 'store':
  169.         config[key] = variable
  170.         print(key,'holds',variable)
  171.        
  172.     else:
  173.         print("mode has not been reconginzed. Possible modes:\n\t- 'get'\n\t-'store'")
  174.  
  175.     config.close()
  176.  
  177.    
  178. def YesNo ():
  179.     """Gets a valid YES/NO answer from user."""
  180.     while True:
  181.         answer = input("> ").upper().strip(' ')
  182.        
  183.         if answer == "YES" or answer == "Y" or answer == "NO" \
  184.         or answer == "NOPE" or answer == "N":
  185.             break
  186.         else:
  187.             print("You did not enter a valid answer. Possibilities are yes/y|no/nope/n")
  188.            
  189.     return answer
  190.  
  191. #       MAIN
  192.  
  193.  
  194. print("Welcome to this backup manager.")
  195. if False: #First Time
  196.     path, bupath = Setup()
  197.     BackUpAll(path, bupath)
  198. else:
  199.     os.chdir(r"W:\Users\Damien\Documents\Code\Code Pyth")
  200.     config = shelve.open('Config')
  201.     path = config['Path2BU']
  202.     bupath = config['BackUpPath']
  203.     #path, bupath = WorkShelf('Path2BU'), WorkShelf('BackUpPath')
  204.     print(path, bupath)
  205.     BackUpAll(path, bupath)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement