1、一个脚本只有一个实例
有这样一个要求,一个python脚本只允许一个实例存在,当这个脚本运行时,你无法通过命令行再一次运行它。
在linux环境下,可以通过对文件加锁的方式实现,脚本第一次启动时,获得一个文件锁,运行期间,这个进程一直拥有这个锁,当第二次在命令行里执行这个脚本时,也会尝试去获得这个文件锁,但是获取失败,进程结束
2、示例代码
#coding=utf-8
import fcntl, sys, time, os
pidfile = 0
def ApplicationInstance():
global pidfile
pidfile = open(os.path.realpath(__file__), "r")
try:
fcntl.flock(pidfile, fcntl.LOCK_EX | fcntl.LOCK_NB) #创建一个排他锁,并且所被锁住其他进程不会阻塞
except:
print "another instance is running..."
sys.exit(1)
if __name__ == "__main__":
ApplicationInstance()
while True:
print 'running...'
time.sleep(1)