歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 用Python寫的一個小小的回收站定時清空程序

用Python寫的一個小小的回收站定時清空程序

日期:2017/3/1 9:49:45   编辑:Linux編程

剛學一段時間的python,突然想寫個小程序來實踐下,剛好處於系統管理的崗位,想到我們在管理Linux系統的時候經常會因為使用rm這個命令的失誤而導致各種悲劇的事發生。
那麼我的想法是,首先,需要在系統的用戶初始化環境配置文件中將rm命令別名下:
alias rm='mv --verbose -f --backup=numbered --target-directory /tmp/trash'

系統添加這個操作後使用rm命令刪除的文件都會被保存在/tmp/trash此目錄下,這就相當於我們Windows當中的回收站了,只是我們需要定時去清理這個回收站
所以下面這段python程序就是為解決此道而行:
#!/usr/bin/python
#coding:utf8
#清除回收站中的文件
import os
log_path = '/tmp/test.log'
trash_path = '/tmp/trash'
file_list = []
def write_log(log_path,file_list):
open_file = open(log_path,'a')
open_file.write('delete file success:\n')
open_file.writelines(file_list)
open_file.close()

def cleartrash(trash_path):
if os.path.exists(trash_path) and os.path.isdir(trash_path):
for root,dirs,files in os.walk(trash_path,topdown=False):
for filename in files:
file_list.append(os.path.join(root,filename)+'\n')
os.remove(os.path.join(root,filename))
for dirname in dirs:
os.rmdir(os.path.join(root,dirname))
print file_list
write_log(log_path,file_list)

cleartrash(trash_path)

代碼中定義兩個方法,一個用於刪除文件,一個用於寫日志,可以將日志追加寫到message文件中,方便系統管理員查看。只要將程序放到計劃任務中執行就OK了。

Copyright © Linux教程網 All Rights Reserved