1

我指的是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

请注意,这条线的右边。

4

1 回答 1

2

Python 缓冲写入stdoutstderr,并在退出时刷新缓冲区。您需要强制刷新才能更早地查看来自 python 的消息:

import sys
print "This is " + sys.argv[0]
sys.stdout.flush()
于 2012-10-21T11:05:24.917 回答