简体   繁体   中英

Python save output to file when run at startup raspberry pi

I have a issue with my raspberry pi that starts up a python script it generates a exception somewhere and I have catched all errors which are printed into the terminal (if running from idle).

But how do I save the printed output to a file when it is running on boot? I found this script below on the internet but it doesn't seem to write the printed text,it creates the file but the content is empty (every 30 sec it should print 'Checking')

This is the code that is being executed after the pi has booted and it shows the GUI elements perfectly (and yes sudo is required due to the GPIO pins)

#!/bin/sh
startx
sudo python /home/pi/python_gui.py > /home/pi/output.log

Hopefully someone knows a answer, thanks in advance!

Without seeing the errors that are being output, it will be very difficult to debug any failing script. So, first you should ensure that you are logging the exception. The line:

sudo python /home/pi/python_gui.py > /home/pi/output.log

will redirect stdout to the file /home/pi/output.log . However, if you want to log errors you also need to redirect stderr . You have two choices here, either redirecting stderr to a different file, or alternatively redirecting it to the same file, by redirecting it to stdout . For example:

To redirect to a new file:

sudo python /home/pi/python_gui.py > /home/pi/output.log 2> /home/pi/error.log

To redirect both to the same file:

sudo python /home/pi/python_gui.py &> /home/pi/output.log

Or:

sudo python /home/pi/python_gui.py > /home/pi/output.log 2>&1

You can find more information and examples on this question .

If you want to update the logfile each time you run, you can append to it using >> instead, eg:

sudo python /home/pi/python_gui.py &>> /home/pi/output.log

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM