Hawarden1963
Hawarden1963

Reputation: 13

Python3.4 - How do I get the PID of a program that was started with Popen? (OS -Raspbian Jessie)

Python 3.4

OS - Raspbian Jessie running on a Raspberry Pi 3

NOTE: The program "gnutv" does NOT have a stop command. It only has an option of a timer to stop the recording.

My question: I'm still fairly new to programming and Python (self/YouTube/books taught). I am writing a program that checks a system for alarms. When an alarm is present, it triggers the program "gnutv" to begin recording video to a file. That was the easy part. I can make the program start, and record video using

Popen(["gnutv", "-out", "file", str(Videofile), str(Channel)])

The program continues to monitor the alarm inputs while the video is recording so it will know when to stop recording. BUT I can't get it to stop recording when the alarm is no longer present. I've attempted to use kill(), terminate(), and others without success (all returned errors indicating I don't know how to use these more complex commands). HOWEVER, I CAN kill the process by switching to the terminal and finding the PID using

pidof 'gnutv'

and then killing it with

kill PID#

So how can I return the PID value I get from the terminal so I can send the kill command to the terminal (again using Popen)? i.e. - Popen(['kill', 'PID#'])

Upvotes: 1

Views: 341

Answers (1)

Dietrich Epp
Dietrich Epp

Reputation: 213318

You don't need to run the kill program itself, you can just call .kill() or .terminate() on the Popen object.

import subprocess
proc = subprocess.Popen(['gnutv', '-out', 'file', str(Videofile), str(Channel)])
# Some time later...

# This is equivalent to running "kill <pid>"
proc.terminate()

# This is equivalent to running "kill -9 <pid>"
proc.kill()

If you really need the pid (hint: you don't) you can get it from the object as well, it's stored in the pid attribute.

print('Spawned gnutv (pid={})'.format(proc.pid))

You really should not be running the kill program, since that program is just a wrapper around the kill() function in the first place. Just call the function directly, or through the wrapper provided by subprocess.

Upvotes: 2

Related Questions