2012-08-15 44 views
2

我必須使用命令基於他們的年齡是刪除文件cron作業:轉換系統命令到Python,文件查找和刪除

find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file' 

但是我想命令集成到一個python腳本其中涉及任務以及也在cron上運行的其他內容。

我知道我可以直接將命令放到Python腳本中,它可能會運行find,但是我很想知道有更多的以Python爲中心的方式來完成此任務,以及可能帶來的其他好處?

回答

2

我的方法是:

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. 

編輯:我測試了它,它沒有工作,所以我固定的代碼,我可以確認它的作品。

+0

您應該使用'os.path.join()'構造路徑名,而不是與「/」連接。 – silvado 2012-08-15 12:27:59

+0

@silvado謝謝:)我現在就添加它。建議的編輯也會起作用。 – hifkanotiks 2012-08-15 12:52:20

1

使用os.popen()

>>>os.popen("find /path/to/file/ -type f -mmin +120|xargs -I file rm 'file'") 

,或者您可以使用subprocess模塊:

>>> from subprocess import Popen, PIPE 
>>> stdout= Popen(['ls','-l'], shell=False, stdout=PIPE).communicate() 
>>> print(stdout)