设为首页 加入收藏

TOP

用Python写的一个小小的回收站定时清空程序
2014-11-24 01:45:45 来源: 作者: 【 】 浏览:1
Tags:Python 一个 小小的 回收站 定时 清空 程序

刚学一段时间的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了。


推荐阅读:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇如何在 AngularJS 中对控制器进行.. 下一篇Android WallpaperManager解析及B..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: