2011-04-15 61 views
0

这是一个实现文件锁定的代码示例,因此应用程序只能打开一个实例。它目前工作,但将锁文件保存在主文件夹(Ubuntu)中。如果应用程序崩溃,锁定文件不会被删除,这是不好的....我在哪里可以更改此Python代码片段以将临时文件保存在tmp文件夹中?

我不能很容易地看到我应该改变代码保存在c:/ tmp文件夹中的代码吗?

#!/usr/bin/python 
# -*- coding: utf-8 -*- 


#implements a lockfile if program already is open 
import os 
import socket 
from fcntl import flock 

class flock(object): 
    '''Class to handle creating and removing (pid) lockfiles''' 

    # custom exceptions 
    class FileLockAcquisitionError(Exception): pass 
    class FileLockReleaseError(Exception): pass 

    # convenience callables for formatting 
    addr = lambda self: '%[email protected]%s' % (self.pid, self.host) 
    fddr = lambda self: '<%s %s>' % (self.path, self.addr()) 
    pddr = lambda self, lock: '<%s %[email protected]%s>' %\ 
           (self.path, lock['pid'], lock['host']) 

    def __init__(self, path, debug=None): 
     self.pid = os.getpid() 
     self.host = socket.gethostname() 
     self.path = path 
     self.debug = debug # set this to get status messages 

    def acquire(self): 
     '''Acquire a lock, returning self if successful, False otherwise''' 
     if self.islocked(): 
      if self.debug: 
       lock = self._readlock() 
       print 'Previous lock detected: %s' % self.pddr(lock) 
      return False 
     try: 
      fh = open(self.path, 'w') 
      fh.write(self.addr()) 
      fh.close() 
      if self.debug: 
       print 'Acquired lock: %s' % self.fddr() 
     except: 
      if os.path.isfile(self.path): 
       try: 
        os.unlink(self.path) 
       except: 
        pass 
      raise (self.FileLockAcquisitionError, 
        'Error acquiring lock: %s' % self.fddr()) 
     return self 

    def release(self): 
     '''Release lock, returning self''' 
     if self.ownlock(): 
      try: 
       os.unlink(self.path) 
       if self.debug: 
        print 'Released lock: %s' % self.fddr() 
      except: 
       raise (self.FileLockReleaseError, 
         'Error releasing lock: %s' % self.fddr()) 
     return self 

    def _readlock(self): 
     '''Internal method to read lock info''' 
     try: 
      lock = {} 
      fh = open(self.path) 
      data = fh.read().rstrip().split('@') 
      fh.close() 
      lock['pid'], lock['host'] = data 
      return lock 
     except: 
      return {'pid': 8**10, 'host': ''} 

    def islocked(self): 
     '''Check if we already have a lock''' 
     try: 
      lock = self._readlock() 
      os.kill(int(lock['pid']), 0) 
      return (lock['host'] == self.host) 
     except: 
      return False 

    def ownlock(self): 
     '''Check if we own the lock''' 
     lock = self._readlock() 
     return (self.fddr() == self.pddr(lock)) 

    def __del__(self): 
     '''Magic method to clean up lock when program exits''' 
     self.release() 

#now testing to see if file is locked = other instance of this program is running already 

lock = flock('tmp.lock', True).acquire() 
if lock: 
    print 'doing stuff' 
else: 
    print 'locked!' 
    exit() 


#end of lockfile 
+2

你说它的Ubuntu的,但然后去提及'C:/'......这是什么? – g19fanatic 2011-04-15 10:16:27

回答

0

在脚本的末尾:

lock = flock('tmp.lock', True).acquire() 

'tmp.lock'的路径在当前目录中的文件。将其更改为您需要的路径,即'c:/tmp-folder/tmp.lock'。然而,作为@ g19fanatic笔记:你在Windows('c:/ ...')还是Linux(Ubuntu)系统上?

+0

谢谢,它是linux,但写了c:出于习惯... – toby 2011-04-15 10:26:21