0

I want to kill a python script that runs on my system from another python script.

I followed this answer and tweaked the code a bit, but got an error:

Traceback (most recent call last):   File "/home/pi/base.py", line 13, in <module>
    check_call(["pkill", "-9", "-f", script])
    File "/usr/lib/python2.7/subprocess.py", line 540, in check_call
        raise CalledProcessError(retcode, cmd)
  CalledProcessError: Command '['pkill', '-9', '-f', '/home/pi/MotionDetector.py']' returned non-zero exit status 1

Code:

from subprocess import check_call
import sys
import time

script = '/home/pi/MotionDetector.py'
check_call(["pkill", "-9", "-f", script])

2 Answers 2

1

This means the pkill call has failed. Two possible reasons that come to mind:

  • it did not actually match any process. pkill would in this case not generate any output and return 1. You can verify this by trying to run pgrep instead of pkill and see what did it return on stdout (should be one or more lines with a PID in case of a match) and/or whether it also returned a non-zero status.

  • it did match, but user under which the pkill has been executed cannot kill the process(s) matched. In that case pkill should generate output on stderr similar to: pkill: killing pid 3244 failed: Operation not permitted

From the pkill(1) man page:

EXIT STATUS
...
       1      No processes matched or none of them could be signalled.
...
Sign up to request clarification or add additional context in comments.

9 Comments

If it's the first case, how can it be resolved? If it's the second - how can I add sudo or get elevated privileges?
@Json I would suggest two things: when the script is running, run ps -ewwo pid,argsps -efw and identify the process(es) you're looking for. You can also paste it here and we can have a look at it together. My initial guess is either a typo, or the script is not actually called as expected and there is something different about command line as seen in the process listing (matched by pkill). You can also try starting with pgrep -f /home/pi/MotionDetector.py and combined with information obtained above safely experiment to find a match (expected PIDs are displayed).
I tried the first command and got this error: error: ' unknown user-defined format specifier "argsps" '
I've tried to write the info to a file with the command below, but the file was empty pgrep -f /home/pi/MotionDetector.py >log.txt 2>&1
My apology that was an editing blunder of mine: ps -ewwo pid,args
|
0

It turns out it was just a bug.

The solution was simple, I copied my script to a new file, deleted the old one and it worked, simple as that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.