1

I am referring to Redirect stderr with date to log file from Cron.

Basically, I have the following files.

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

The python_1.py calling shellscript_2.sh from within it script:

#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()

And this is the content of cronlog.sh exactly from the reciert #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"

And I have cronjob to run this and redirected to the log file, but no matter what I have tried the content from shellscript_2.sh got written to log first instead of python_1.py.

Here's the sample log output:

[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

Note that by right this line.

4

1 に答える 1

2

Python buffers writes to stdout and stderr, and flushes the buffer on exit. You need to force a flush to see your message from python earlier:

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