0

I have a Pi 4 with bookworm, running a python 3 script.

The python script generates logging output to stdout (to the terminal) when run from a prompt. I want to run the script from cron and capture the output to a file. These lines are part of a cron-run.sh script started from cron.

#!/bin/bash MYLOGFILE=/home/pi/logs/python-log.txt python /home/pi/mypython.py -switch param1 param2 >> $MYLOGFILE 

The log file, /home/pi/logs/python-log.txt is created as a zero byte file, and remains zero bytes as the python script runs.

All paths are fully specified, which is the issue often mentioned with cron-related problems. The full path to python is not needed, since I can see it running when started from cron with `ps aux | grep "python"'

Why does redirection of python stdout to a file not work when started from cron?

cron runs a script which contains the lines above. crontab looks like this:

# m h dom mon dow command */30 * * * * /home/pi/cron-run.sh 

    3 Answers 3

    1

    Try to redirect both stdout and stderr, something like this:

    python /home/pi/mypython.py -switch param1 param2 >> $MYLOGFILE 2>&1 

    stderr is the stream used to log error messages from the python command.

    1
    • That was it. The python script uses the python logging module. I'm not sure why, but apparently it routes all output to stderr. That's not apparent until you try to redirect.
      – tim11g
      CommentedFeb 23 at 20:13
    0

    The script is probably dying early with a stack trace and error message to stderr. Capture stderr too and you should see the error message in your python-log.txt. To capture stderr too append 2>&1 to the end of the python command

      0

      For me the solution was as simple as changing the file access mode in the archive config's python for the binary archive that the command generate. Look at the permissions read, write and create, maybe, it don't has write, look similar to: with open(mycsvfile, "w") as outfile: writer = csv.writer(outfile) writer.writerows([s.strip().encode("utf-8") for s in row ]for row in list_of_rows) outfile.close() and them chmod +x

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.