When you’re working on a project that changes frequently, backing up your work becomes essential. Whether it’s a software development project, a creative endeavor, or any ongoing work that involves constant updates, the last thing you want is to lose progress due to an unforeseen issue. However, manual backups are tedious and easy to forget. Enter BackMeUp — a Python script designed to handle your backups automatically, ensuring that every version of your files is preserved without disrupting your workflow.
What is BackMeUp?
BackMeUp is a free advanced Python utility that automates the backup process for any file or folder, specifically catering to projects that change often. The script not only backs up files at a scheduled time but also checks if the target folder or program is in use. If it is, the script waits until the folder is no longer in use before proceeding with the backup. Once ready, it creates a timestamped folder in the backup directory, ensuring that each backup is neatly organized and easy to restore.
How It Works
BackMeUp operates by scheduling backups at a specific time of day, checking if the target folder or program is currently in use, and if not, it backs up the folder by creating a new subfolder in the backup directory. This subfolder is named after the original file with the current timestamp appended, making it easy to track changes over time.
Here’s how you can set it up and start backing up your projects effectively.
Setting Up BackMeUp Pro
To use BackMeUp, you’ll need to create a Python script named backmeup.py
. This script can be stored in any directory where you manage your projects or utilities.
1. Create the Script File
Begin by creating the Python script:
touch backmeup.py
2. Write the Script
Open backmeup.py
in your preferred text editor and input the following code:
import os
import shutil
import time
import psutil
from datetime import datetime
# Define the source directory to back up
SOURCE_DIR = "/path/to/source/directory"
# Define the destination directory for backups
DEST_DIR = "/path/to/destination/directory"
# Time of day to run the backup (24-hour format)
BACKUP_TIME = "02:00"
def is_in_use(directory):
# Check if any file in the directory is currently open or in use
for proc in psutil.process_iter(['pid', 'name', 'open_files']):
for file in proc.info['open_files'] or []:
if file.path.startswith(directory):
return True
return False
def backup_files():
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_subdir = os.path.join(DEST_DIR, f"{os.path.basename(SOURCE_DIR)}_{timestamp}")
if not os.path.exists(backup_subdir):
os.makedirs(backup_subdir)
for root, dirs, files in os.walk(SOURCE_DIR):
for file in files:
source_file = os.path.join(root, file)
relative_path = os.path.relpath(source_file, SOURCE_DIR)
dest_file = os.path.join(backup_subdir, relative_path)
# Create destination directory if it doesn't exist
os.makedirs(os.path.dirname(dest_file), exist_ok=True)
shutil.copy2(source_file, dest_file)
print(f"Backup completed successfully at {timestamp}.")
def run_backup_at_time():
while True:
current_time = time.strftime("%H:%M")
if current_time == BACKUP_TIME:
print("It's time for a backup!")
if is_in_use(SOURCE_DIR):
print("The source directory or program is in use. Waiting...")
while is_in_use(SOURCE_DIR):
time.sleep(60) # Wait for a minute before checking again
else:
backup_files()
time.sleep(86400) # Sleep for 24 hours before the next backup
if __name__ == "__main__":
run_backup_at_time()
How the Script Works
- SOURCE_DIR and DEST_DIR: These variables define the source directory you want to back up and the destination directory where backups will be stored. Replace
"/path/to/source/directory"
and"/path/to/destination/directory"
with the actual paths on your system. - BACKUP_TIME: Set the time of day when the backup should occur. The format is
"HH:MM"
in 24-hour time. - is_in_use() Function: This function checks if any file within the source directory is currently in use. It leverages the
psutil
library to monitor open files and processes, ensuring that backups don’t happen while files are being modified. - backup_files() Function: This function creates a new subfolder in the destination directory with the source directory’s name and the current timestamp. It then copies all files from the source to the backup folder, preserving the directory structure and file timestamps.
- run_backup_at_time() Function: This function continuously checks the time and triggers the backup process when the scheduled time is reached. If the folder is in use, the script waits until it becomes free before proceeding.
Running the Script
To run BackMeUp, open your terminal, navigate to the directory where backmeup.py
is located, and execute the script:
python backmeup.py
The script will now run in the background, checking the time and initiating backups at the scheduled time each day.
Thank you for following along with this tutorial. We hope you found it helpful and informative. If you have any questions, or if you would like to suggest new Python code examples or topics for future tutorials/articles, please feel free to join and comment. Your feedback and suggestions are always welcome!
You can find the same tutorial on Medium.com.