Tim
Tim

Reputation: 105

pid of executing python script using psutil

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?

Upvotes: 4

Views: 5525

Answers (1)

Tim
Tim

Reputation: 105

os.getpid()

and

How to terminate process from Python using pid?

was the answer.

Upvotes: 5

Related Questions