• notice
  • Congratulations on the launch of the Sought Tech site

How to prohibit multiple execution of script in python

Have you ever encountered such a requirement in the process of writing python scripts? To prevent this script from running only once in the system at the same time, it cannot run at the same time. I have encountered it twice, so how to achieve such a requirement? Don't worry, please follow Meditation to realize the function of prohibiting repeated execution of python scripts.

There are two implementation methods:

The first is to use port occupancy to prevent repeated execution:

code show as below:

HOST='127.0.0.1'
 PORT=5555try:
   s = socket.socket()
   s.bind((HOST, PORT))
   main()
   s.close()exceptKeyboardInterrupt:
   s.close()except:print(' * already has an instance, so exit.')
   exit(0)

explain:

The principle is that as soon as the program is executed, it will listen to the specified port 5555. If it is not executed, then this port can be successfully monitored. On the contrary, if the port monitoring fails, it means that the port is already occupied, then the program will report an error. At this time It will jump directly to except: to execute. In this way, the program will end and will not be repeated.

where main() is the main function you want to execute. This is the business logic code you want to implement.

The second way is to use the form of process ID to judge:

Code:

#!/usr/bin/python#coding:utf-8import osimport psutilimport timedef write_pid():
   pid = os.getpid()
   fp = open("pid.log",'w')
   fp.write(str(pid))
   fp.close()def read_pid():
   if os.path.exists("pid.log"):
       fp = open("pid.log",'r')
       pid = fp.read()
       fp.close()
       return pid    else:
       return Falsedef write_log(log_content):
   time_now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
   log_content = time_now+"---->"+log_content+os.linesep
   fp = open('recognition.log','a+')
   fp.write(log_content)
   fp.close()def run():
   pid = read_pid()
   #print pid
   pid = int(pid)
   if pid:
       running_pid = psutil.pids()
       if pid in running_pid:
           log_content =  "process is running..."
           write_log(log_content)
       else:
           write_pid()
           time.sleep(20)
   else:
       write_pid()
       time.sleep(20)if __name__ == "__main__":
   run()

This method will generate two files in the script execution directory, one is a file that records the process ID, and the other is a log file. Okay, that's it for the tutorial, I should go home too!

Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+