Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Python Script is already running

i would like my Python script to check, if it is already running and if yes, kill the old process. i tried this, but it doesn't really work...

import os
import subprocess
import signal

process_name = "python " + os.path.abspath(__file__)
proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE)

# Kill process.
for pid in proc.stdout:
    os.kill(int(pid), signal.SIGTERM)
    # Check if the process that we killed is alive.
    try:
        os.kill(int(pid), 0)
        raise Exception("""wasn't able to kill the process
                          HINT:use signal.SIGKILL or signal.SIGABORT""")
    except OSError as ex:
        continue

It doesn't kill the old process and runs multiple times now.

like image 449
Martin Avatar asked Apr 22 '16 16:04

Martin


2 Answers

This question is very similar to Check to see if python script is running

I suggest you use the PidFile module, it will handle everything for you.

import pidfile
import time

print('Starting process')
try:
    with pidfile.PIDFile():
        print('Process started')
        time.sleep(30)
except pidfile.AlreadyRunningError:
    print('Already running.')

print('Exiting')

Try to run twice this script with two terminals

I am not related to the owner of the library, I just found it

like image 200
aster94 Avatar answered Sep 17 '22 13:09

aster94


My current solution looks like this (on OSX). I am using pgrep in combination with regexp

import subprocess

cmd = ['pgrep -f .*python.*testing03.py']
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
my_pid, err = process.communicate()

if len(my_pid.splitlines()) >0:
   print("Running")
   exit()
else:
  print("Not Running")

As far as i have tested this should work even if the python string differs. Location of the script doesn't matter either

like image 23
MickeMannen Avatar answered Sep 19 '22 13:09

MickeMannen