2015-03-13 49 views
0

我正在使用python子流程將日誌文件發送給運行python腳本的用戶。但是,每次用戶運行腳本時,都會覆蓋日誌文件。這裏是我在Python代碼中使用的unix子進程命令:更改python子流程中的輸出日誌文件名以使其唯一

subprocess.Popen("mail -s 'logfile.log attached' -r [email protected] -a logfile.log [email protected] &> /dev/null",shell=True) 

我怎樣才能使日誌文件的名稱唯一?也許incremant日誌文件名稱爲logfile1.log,logfile2.log等?

訣竅是如何實現這個子過程?

回答

1

嘗試使用timestamp來生成日誌文件名稱。關於在子進程中使用該命令,命令不過是一個字符串。因此,它很簡單,只要

import time 
fileName = "logfile." + str(time.time()) + ".log" # use your logic to generate logFile name. 
command = "mail -s '%s attached' -r [email protected] -a %s [email protected] &> /dev/null" %(fileName, fileName) 
subprocess.Popen(command,shell=True) 
3

你也可以用日期時間模塊做到這一點:

import datetime 
filename = "logfile-%s.log" % datetime.datetime.today().isoformat() 
command = "mail -s '{0} attached' -r [email protected] -a {0} [email protected] &> /dev/null".format(filename) 
subprocess.Popen(command, shell=True) 

日誌文件的名稱看起來像logfile-2015-03-13T21:37:14.927095.log

相關問題