2012-10-21 64 views
1

我指的是Redirect stderr with date to log file from Cron重定向stderr與來自cron的日誌文件

基本上,我有以下文件。

[email protected]:/home/osaka# ls -l cronlog.sh python_1.py shellscript_2.sh 
-rwxr-xr-x 1 root root 153 Oct 19 16:49 cronlog.sh 
-rwxr-xr-x 1 root root 694 Oct 19 18:28 python_1.py 
-rwxr-xr-x 1 root root 96 Oct 19 18:27 shellscript_2.sh 

python_1.py調用從內它的腳本shellscript_2.sh

#python_1.py 
#!/usr/bin/python 

import os, sys, subprocess 

def command(): 
    return os.system('/home/osaka/shellscript_2.sh') 

print "This is " + sys.argv[0] 
command() 

這是cronlog.sh正是從reciert#7145544內容:

#cronlog.sh 
#!/bin/sh 

echo "[`date +\%F-\%T`] Start executing $1" 
"[email protected]" 2>&1 | sed -e "s/\(.*\)/[`date +\%F-\%T`] \1/" 
echo "[`date +\%F-\%T`] End executing $1" 

而且我的cronjob運行這並重定向到日誌文件,但無論我嘗試從shellscript_2.sh的內容寫入日誌而不是python_1.py

下面是示例日誌輸出:

[2012-10-19-18:45:31] Start executing /home/achinnac/osaka/python_1.py 
[2012-10-19-18:45:31] This is /home/achinnac/osaka/shellscript_2.sh 
[2012-10-19-18:45:31] This is /home/achinnac/osaka/python_1.py 
[2012-10-19-18:45:31] End executing /home/achinnac/osaka/python_1.py 

注意,通過右鍵這條線。

回答

2

Python緩衝區寫入stdoutstderr,並在退出時刷新緩衝區。您需要強制刷新以查看來自python的消息:

import sys 
print "This is " + sys.argv[0] 
sys.stdout.flush() 
+0

哇!這解決了我的問題。非常感謝。 – achinnac

相關問題