<s> import errno <EOL> import os <EOL> import tempfile <EOL> class Pidfile ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , fname ) : <EOL> self . fname = fname <EOL> self . pid = None <EOL> def create ( self , pid ) : <EOL> oldpid = self . validate ( ) <EOL> if oldpid : <EOL> if oldpid == os . getpid ( ) : <EOL> return <EOL> raise RuntimeError ( "<STR_LIT>" <EOL> "<STR_LIT>" % ( os . getpid ( ) , self . fname ) ) <EOL> self . pid = pid <EOL> if self . fname : <EOL> fdir = os . path . dirname ( self . fname ) <EOL> if fdir and not os . path . isdir ( fdir ) : <EOL> raise RuntimeError ( "<STR_LIT>" <EOL> "<STR_LIT>" % fdir ) <EOL> fd = os . open ( self . fname , os . O_CREAT | os . O_WRONLY ) <EOL> else : <EOL> fd , self . fname = tempfile . mkstemp ( dir = fdir ) <EOL> os . write ( fd , "<STR_LIT>" . format ( self . pid ) . encode ( '<STR_LIT:utf-8>' ) ) <EOL> os . close ( fd ) <EOL> os . chmod ( self . fname , <NUM_LIT> ) <EOL> def rename ( self , path ) : <EOL> self . unlink ( ) <EOL> self . fname = path <EOL> self . create ( self . pid ) <EOL> def unlink ( self ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> with open ( self . fname , "<STR_LIT:r>" ) as f : <EOL> pid1 = int ( f . read ( ) or <NUM_LIT:0> ) <EOL> if pid1 == self . pid : <EOL> os . unlink ( self . fname ) <EOL> except : <EOL> pass <EOL> def validate ( self ) : <EOL> """<STR_LIT>""" <EOL> if not self . fname : <EOL> return <EOL> try : <EOL> with open ( self . fname , "<STR_LIT:r>" ) as f : <EOL> wpid = int ( f . read ( ) or <NUM_LIT:0> ) <EOL> if wpid <= <NUM_LIT:0> : <EOL> return <EOL> try : <EOL> os . kill ( wpid , <NUM_LIT:0> ) <EOL> return wpid <EOL> except OSError as e : <EOL> if e . args [ <NUM_LIT:0> ] == errno . ESRCH : <EOL> return <EOL> raise <EOL> except IOError as e : <EOL> if e . args [ <NUM_LIT:0> ] == errno . ENOENT : <EOL> return <EOL> raise </s>
