首页 / 操作系统 / Linux / 用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:
") 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)+"
") 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了。推荐阅读: 《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htmPython 网站文件及数据库备份脚本 http://www.linuxidc.com/Linux/2012-06/62346.htmPython文件处理:读取文件 http://www.linuxidc.com/Linux/2013-08/88496.htm如何发布自定义的Python模块 http://www.linuxidc.com/Linux/2013-08/88495.htmPython爬虫多线程抓取代理服务器 http://www.linuxidc.com/Linux/2013-07/87289.htmPython中re(正则表达式)模块详解 http://www.linuxidc.com/Linux/2013-08/88588.htmPython 的详细介绍 :请点这里Python 的下载地址 :请点这里
收藏该网址