How to stop my python script when running another python script?

I want to know how I can stop the current current python script when it is already running.

To be clear, I want to write it in my own python script. So, the most important thing, in the main method, it checks if my python script is working or not. If it is running, I want to exit with an error message.

I am currently trying to use this code:

if os.system("ps ax | grep sample_python.py") == True: print "fail" exit(0) else: print "pass" 

The above code looks like grepping the name of python .. but it always goes into else, instead of going into the if loop and exiting.

So, for testing, I run my script, and on the other terminal I run my script again. The first script does not stop, but the second python does not enter the if loop to print an error message.

How can i fix this?


Ok, I found a dumb thing, and I want to see if anyone can help me get around this. So I decided to kill python, which runs only if another python is currently running. but stupid thing .. since I run my python and run code verification inside this python .. it will always exit .. because as soon as I run python, the PID will be created and will be launched ...

So, python launch β†’ pid is created and running β†’ check if python is running β†’ yes python is running β†’ exit.

I want to see if there is a way to make python run β†’ check if python is running or not β†’ if it is running, kill the current python and not the one that was running.

+2
python linux unix
source share
6 answers

A lock file with the PID of the current process is a more systematic way to do this. The program simply checks at the beginning whether the PID file 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 overwrites) the PID file and locks it.

Locking flock / lockf has the advantage that the operating system automatically removes the lock if the program terminates.

See here how to do this in Python:

Python: module for creating a PID-based lock file?

+7
source share

os.system () returns the completion value of the command being executed. If ps was successful, it returns 0, which is not equivalent to True. You can explicitly test if the command returned zero, which should lead you to the if block.

Edit: this requires os.subprocess . These four teams 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 a list of running processes that output to grep to print everything except your script (or bash instances in the code sample), pipes that output to wc to get the number of lines and then requests this process for its stdout, which is the counter of the script instances that are currently running. You can then use this count variable in an if statement, where if more than one instance is running, you can abort.

0
source share

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" 
0
source share

Instead of using grep , why not create a lock file? One instance of your program creates a file in a known place and deletes it when exiting. Any other instance should check for the existence of this file and continue to work only if it already exists.

The os.open() function has special 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 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 by setting, say, import time; time.sleep(20) import time; time.sleep(20) after `print (" Pass ") and running multiple instances of this script; all but one must fail.

0
source share

Because os.system ("ps ax | grep sample_python.py") returns 0. This is not true.

Take a look at this question: Assign os.system output to a variable and not display it on screen

You have to write

 os.popen('cat /etc/services').read() 

But in this way you will always go to "unsuccessful" because your script is already running. You should count the number of rows returned ...

Look here as a variant of one instance:

Python: one instance of a program

I wrote such a script. I created a file with any name at the beginning and deleted at the end. It was a daemon script. At the beginning, I checked if this file exists.

A good option here. Provide one instance of the application on Linux :

 import fcntl pid_file = 'program.pid' fp = open(pid_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: # another instance is running sys.exit(1) 
-one
source share

You can use the cross-platform psutil library to iterate over the processes, analyze the command line of each process and check if it is a python process with the same script path, then you can either stop execution when you find only one, or destroy / 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(): if len(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 
-one
source share

All Articles