I have a python script that continuously saves data to a CSV file and is started as soon as the Pi starts up using crontab reboot. Does anyone know how I stop the script from within the Raspberry Pi terminal so that the CSV file is closed/saved properly? Thanks.

The classical way to do that is to have the script save its process number (PID) to a well known file, then later you can read the PID from that file and use it to kill the process. The customary place for such files is /var/run/scriptname.pid or /run/scriptname.pid, but if your process doesn't have access rights to these directories, any directory will do.

The alternative is to use ps to search for the process to get the PID and again use it to kill the process.

If you have buffered output, you should catch SIGTERM (and other signals) so that your program writes the output buffers to the files.

You can also have your script check for some condition and terminate if that condition is true.

If you know the name of the python script, but not the process ID (PID):

  1. print the PID: ps -C placeholder_for_script_name -o pid
  2. kill the corresponding process: kill placeholder_for_pid_of_your_script

If you do not know the name of the python script, nor the PID:

  1. Print a process tree by ps axjf and look over the "COMMAND" column for the script name respectively the "PID" column to get its PID.
  2. kill the corresponding process: kill placeholder_for_pid_of_your_script
  • 1
    You may need to use sudo to kill the script depending on the user account it's running from. – Charemer Nov 9 at 16:12

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.