2010-06-02 62 views
1

可能重复:
Python: single instance of program制作一个python脚本只能在同一时间运行一次

我希望做一个python脚本是在独特之处在于它可以一次只能运行一次。例如,如果我运行脚本并第二次打开同一脚本的另一个会话,并且第一个会话仍在运行,那么第二个会话将会退出并不执行任何操作。任何人都知道我可以如何实现这个?

+0

http://stackoverflow.com/questions/380870/ python-single-instance-of-program http://stackoverflow.com/questions/220525/ensuring-a-single-instance-of-an-application-in-linux http://stackoverflow.com/questions/1900979/如何避免 - 程序的多个实例 – 2010-06-02 16:19:56

+0

已经回答[这里](http://stackoverflow.com/questions/380870/python-single-instance-of-program)。 – RSabet 2010-06-02 16:18:39

回答

0

一个穷人的解决方案是使用基于文件的锁。如果您使用os.open()打开文件,则会有一个标志允许对该文件进行排它锁定。请参阅this以供参考。

1

从未写过之前蟒蛇,但是这是我刚刚在mycheckpoint实施,以防止它被通过的crond启动了两次或更多:

import os 
import sys 
import fcntl 
fh=0 
def run_once(): 
    global fh 
    fh=open(os.path.realpath(__file__),'r') 
    try: 
     fcntl.flock(fh,fcntl.LOCK_EX|fcntl.LOCK_NB) 
    except: 
     os._exit(0) 

run_once()