将系统命令转换为python以进行文件搜索和删除
我有一个cron作业,它使用以下命令根据文件的年龄删除文件:将系统命令转换为python以进行文件搜索和删除,python,find,Python,Find,我有一个cron作业,它使用以下命令根据文件的年龄删除文件: find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file' 不过,我想将该命令集成到一个python脚本中,该脚本涉及到该任务以及在cron上运行的其他内容 我知道我可以将命令按原样链接到Python脚本中,它可能会运行find,但是我想知道有一种更以Python为中心的方法来实现这一点,以及它可能带来的其他好处?使用os.popen() 或者您可以使用子流程模块:
find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file'
不过,我想将该命令集成到一个python脚本中,该脚本涉及到该任务以及在cron上运行的其他内容
我知道我可以将命令按原样链接到Python脚本中,它可能会运行find,但是我想知道有一种更以Python为中心的方法来实现这一点,以及它可能带来的其他好处?使用os.popen()
或者您可以使用子流程
模块:
>>> from subprocess import Popen, PIPE
>>> stdout= Popen(['ls','-l'], shell=False, stdout=PIPE).communicate()
>>> print(stdout)
我的方法是:
import os
import time
def checkfile(filename):
filestats = os.stat(filename) # Gets infromation on file.
if time.time() - filestats.st_mtime > 120: # Compares if file modification date is more than 120 less than the current time.
os.remove(filename) # Removes file if it needs to be removed.
path = '/path/to/folder'
dirList = os.listdir(path) # Lists specified directory.
for filename in dirList:
checkfile(os.path.join(path, filename)) # Runs checkfile function.
编辑:我测试了它,它不起作用,所以我修复了代码,我可以确认它起作用。你应该使用
os.path.join()
来构造路径名,而不是用“/”。@silvado谢谢:)串联,我现在就添加它。建议的编辑也会奏效。
import os
import time
def checkfile(filename):
filestats = os.stat(filename) # Gets infromation on file.
if time.time() - filestats.st_mtime > 120: # Compares if file modification date is more than 120 less than the current time.
os.remove(filename) # Removes file if it needs to be removed.
path = '/path/to/folder'
dirList = os.listdir(path) # Lists specified directory.
for filename in dirList:
checkfile(os.path.join(path, filename)) # Runs checkfile function.