기존에 있던 lockfile.pidlockfile 모듈을 참조하여 pid 부분을 수정
import os import errno from win32com.client import GetObject class PIDLockError(Exception): pass class AlreadyLocked(PIDLockError): def __init__(self, path): self.path = path
def __str__(self): return "%s is already locked" % self.path class LockFailed(PIDLockError): def __init__(self, path): self.path = path def __str__(self): return "failed to create %s" % self.path class PIDLockFile(object): def __init__(self, path): self.path = path def read_pid(self): return self.read_pid_from_pidfile() def is_locked(self): return os.path.exists(self.path) def i_am_locking(self): running_process = [] wmi = GetObject('winmgmts:') processes = wmi.InstancesOf('win32_Process') for pro in processes: running_process.append(pro.Properties_('ProcessId').value)
if self.is_locked(): if self.read_pid() in running_process: return True return False def acquire(self): if not self.i_am_locking(): self.break_lock()
try: self.write_pid_to_pidfile() except OSError, exc: if exc.errno == errno.EEXIST: raise AlreadyLocked(self.path) else: raise LockFailed(self.path) else: return def release(self): self.remove_existing_pidfile() def break_lock(self): self.remove_existing_pidfile()
def read_pid_from_pidfile(self): pid = None try: pidfile = open(self.path, 'r') except IOError: pass else: line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid def write_pid_to_pidfile(self): pidfile_fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY) pidfile = os.fdopen(pidfile_fd, 'w') pid = os.getpid() pidfile.write("%s\n" % pid) pidfile.close() def remove_existing_pidfile(self): if self.is_locked(): os.remove(self.path) # example import os import traceback import pidlockfile import PIDLockFile, PIDLockError def main(): pid_file = os.path.join("C:\\", "run", "run.pid") plock = PIDLockFile(pid_file) try: plock.acquire() print "hellow" plock.release()
except PIDLockError, exc: print exc except Exception, exc: print traceback.format_exc()
if __name__ == "__main__": main() |
'Python' 카테고리의 다른 글
daemonizing (0) | 2016.12.22 |
---|---|
Threading (0) | 2016.12.22 |
cygwin + ssh + rsync (0) | 2016.12.10 |
remove ^M(Carriage Return) (0) | 2016.11.30 |
sqlalchemy (0) | 2016.11.28 |