user3327050 user3327050 - 1 year ago 106
Linux Question

How to grab a programs PID using python

i'm trying to grab openvpn pid then check to see if its running but this code doesnt seem to work. it tells me 'pid' isn't an integer when the output is '432'

import psutil
import time
import os
import subprocess

proc = subprocess.Popen(["pgrep openvpn"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
out = out.strip()
print ("openvpn",out)
pid = out
while True:
if psutil.pid_exists(pid):
print "a process with pid %d exists" % pid
print "a process with pid %d does not exist" % pid

Answer Source

'432' is not an integer; it's a string that holds digits. Convert it to an integer using int().