Skip to content Skip to sidebar Skip to footer

How Can I Stop My Python Script When Another Python Script Is Running?

I want to know how I can stop my current python script when it is already running. To be clear, I want to write it in my own python script. So the very first thing, in main method,

Solution 1:

A lockfile with PID of the running process is a more systematic way how to this. Program just checks at the start whether a PID file both exists and is locked (flock or lockf); if so, it means that another instance of this program is still running. If not, it creates (or rewrites) the PID file and locks it.

The flock/lockf lock has the advantage that operating system automatically removes the lock in case of program termination.

See here how to do this in Python:

Python: module for creating PID-based lockfile?

Solution 2:

Instead of using grep, why not create a lock file? One instance of your program creates a file in a known location, and deletes it upon exit. Any other instance has to check for the existence of that file, and should only continue running if it already exists.

The os.open() function has specific flags for this:

import os

LOCKFILE_LOCATION = "/path/to/lockfile"try:
    os.open(LOCKFILE_LOCATION, os.O_CREAT|os.O_WRONLY|os.O_EXCL)
    # Maybe even write the script's PID to this file, just in case you need# to check whether the program died unexpectedly.except OSError:
    # File exists or could not be created. Can check errno if you really# need to know, but this may be OS dependent.print("Failed to create lockfile. Is another instance already running?")
    exit(1)
else:
    print("Pass")
    # Run the rest of the program.# Delete the file
    os.remove(LOCKFILE_LOCATION)

Try this out by putting, say, import time; time.sleep(20) after `print("Pass") and running multiple instances of this script; all but one should fail.

Solution 3:

More pythonic way:

import os
import psutil

script_name = os.path.basename(__file__)
if script_name in [p.name() for p in psutil.get_process_list()]:
   print"Running"

Solution 4:

os.system() returns the exit value of the command that was run. If the ps was successful, it returns 0, which is not equivalent to True. You could explicitly test if the command returned zero, which should bring you into the if block.

Edit: To do this needs os.subprocess. These four commands should get what you want.

p1 = subprocess.Popen(['ps', 'ax'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'bash'], stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['wc', '-l'], stdin=p2.stdout, stdout=subprocess.PIPE)
count = int(p3.stdout.read())
if count > 1:
    print('yes')

Replace "bash" with the name of your script. What this does is get the list of running processes, pipes that output to grep to winnow out all but your script (or bash instances in the code sample), pipes that output to wc to get a count of lines, and then asks that process for its stdout which is the count of the instances of the script that are currently running. You can then use that count variable in an if statement, where if there is more than one instance running, you could abort the run.

Solution 5:

you can use the cross-platform library psutil to iterate over processes, parse the commanline of each process and check if it's a python process with the same script path, then you can either stop the execution when you find only one or kill/stop the old instance/s and continue with the new one.

import os
import psutil
import sys

for proc in psutil.process_iter():
    if"python"in proc.name():
        iflen(proc.cmdline()) > 1:
            script_path = sys.argv[0]
            proc_script_path = proc.cmdline()[1]
            if script_path.startswith("." + os.sep) or script_path.startswith(".." + os.sep):
                script_path = os.path.normpath(os.path.join(os.getcwd(), script_path))
            if proc_script_path.startswith("." + os.sep) or proc_script_path.startswith(".." + os.sep):
                proc_script_path = os.path.normpath(os.path.join(proc.cwd(), proc_script_path))
            if  script_path == proc_script_path and os.getpid() != proc.pid:
                #proc.kill() # you can terminate all the other instances
                sys.exit() # or your way, terminate this newer instance here

Post a Comment for "How Can I Stop My Python Script When Another Python Script Is Running?"