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:
s = socket.socket()
s.close()except:print(' * already has an instance, so exit.')
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:
#!/usr/bin/python#coding:utf-8import osimport psutilimport timedef write_pid():
pid = os.getpid()
fp = open("pid.log",'w')
fp = open("pid.log",'r')
pid = fp.read()
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+')
pid = read_pid()
pid = int(pid)
running_pid = psutil.pids()
if pid in running_pid:
log_content = "process is running..."
time.sleep(20)if __name__ == "__main__":
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!