bcb-0016
1.000
Proposed solution
```python
import os
import glob
import subprocess
def task_func(directory, backup_dir='/path/to/backup'):
"""
Backup all '.log' files in a specified directory to a tar.gz file and delete the original files after backup.
The backup file is named 'logs_backup.tar.gz' and placed in the specified backup directory.
Parameters:
- directory (str): The directory that contains the log files to be backed up.
- backup_dir (str, optional): The directory where the backup file will be saved.
Default is '/path/to/backup'.
Returns:
- str: The path to the backup file if logs are found, otherwise returns a message 'No logs found to backup'.
Raises:
- FileNotFoundError: If the specified directory does not exist.
Requirements:
- subprocess
- glob
- os
Example:
>>> task_func('/path/to/logs')
'/path/to/backup/logs_backup.tar.gz'
>>> task_func('/path/to/logs', '/alternative/backup/dir')
'/alternative/backup/dir/logs_backup.tar.gz'
"""
# Check if the directory exists
if not os.path.exists(directory):
raise FileNotFoundError(f"The specified directory '{directory}' does not exist.")
# Find all .log files in the directory
log_files = glob.glob(os.path.join(directory, "*.log"))
# If no log files found, return message
if not log_files:
return "No logs found to backup"
# Create backup directory if it doesn't exist
os.makedirs(backup_dir, exist_ok=True)
# Create the backup file path
backup_file = os.path.join(backup_dir, "logs_backup.tar.gz")
# Create tar.gz archive with all log files
try:
subprocess.run([
"tar",
"-czf",
backup_file,
*log_files
], check=True)
except subprocess.CalledProcessError:
raise Exception("Failed to create backup archive")
# Delete original log files after successful backup
for file in log_files:
os.remove(file)
return backup_file
```Test output (stdout)
.... [100%] 4 passed in 0.03s
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.