user3327050 user3327050 - 2 months ago 20
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
time.sleep(5)
while True:
if psutil.pid_exists(pid):
print "a process with pid %d exists" % pid
time.sleep(120)
else:
print "a process with pid %d does not exist" % pid
time.sleep(5)
os.system("")

Answer

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