使用来自cron的日志文件重定向stderr

时间:2012-10-21 10:59:38

标签: python shell logging crontab

我指的是Redirect stderr with date to log file from Cron

基本上,我有以下文件。

root@ubuntu:/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的内容,完全来自于收件人#7145544:

#cronlog.sh
#!/bin/sh

echo "[`date +\%F-\%T`] Start executing $1"
"$@" 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

请注意,在此行右侧。

1 个答案:

答案 0 :(得分:2)

Python缓冲写入stdoutstderr,并在退出时刷新缓冲区。你需要强制刷新以便在早些时候从python中看到你的消息:

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