4

OS: Jessie

Python: 2.7

I want to use psutil to terminate my script I am currently executing. My problem is that I would like to kill it with the ID but I don't know how to get the pid of my script.

I know I can terminate with the names of processes, but I think thats not a pretty solution.

Has anyone an idea how to make this work?

I have set up my Pi with the PiCamera, a GUI and some sensors. I am using the cv2 library and the problem is that the windows won't close. Therefore, I googled how to close them but there wasn't any solution I could use. Killing the process is ok for me.

EDIT:

import psutil

def on_terminate(proc):
    print("process {} terminated with exit code {}".format(proc, proc.returncode))

procs = psutil.Process().children()
for p in procs:
    p.terminate()
gone, still_alive = psutil.wait_procs(procs, timeout=3, callback=on_terminate)
for p in still_alive:
    p.kill()

I found this snippet in the documentation. How can I make this run with pid's?

Tim
  • 105
  • 1
  • 6
  • can you give the link to your script? with that, solving your problem would be easier. – Kshitij Mittal Sep 22 '17 at 12:02
  • do you want to kill your own script? why not `sys.exit()`? – Jean-François Fabre Sep 22 '17 at 12:02
  • Welcome to stackoverflow. Please, could you provide some code of your specific problem. That prove how far did you try and it will help other members to understand your problem better, at the time, you will give them a context of your issue. Please, check these links: https://stackoverflow.com/help/mcve and https://stackoverflow.com/help/how-to-ask – Kenzo_Gilead Sep 22 '17 at 12:03
  • How are you executing the script? For example, `subprocess.Popen` objects have a [`pid`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.pid) attribute. – holdenweb Sep 22 '17 at 12:04
  • sorry, I didn't mention what I want to do. – Tim Sep 22 '17 at 12:05
  • And, rather than linking to your script, edit your question (enter the code then select it and hit CTRL/K or Cmd/K to format it). Try to keep your example small. – holdenweb Sep 22 '17 at 12:06
  • with `python script.py` . I've tried using `subprocess.Popen` but there wasn't a success – Tim Sep 22 '17 at 12:22

1 Answers1

5
os.getpid()

and

How to terminate process from Python using pid?

was the answer.

Tim
  • 105
  • 1
  • 6