On 18/06/07, Evan Klitzke <[EMAIL PROTECTED]> wrote: > On 6/18/07, Robin Becker <[EMAIL PROTECTED]> wrote: > > I wish to prevent a python script from running twice; it's an hourly job, > > but > > can take too long. > > > > My simplistic script looks like > > > > > > ....... > > def main(): > > fn = 'MARKER' > > if os.path.isfile(fn): > > log('%s: hourly job running already' % formatTime()) > > else: > > f = open(fn,'w') > > f.write(str(os.getpid())) > > f.close() > > try: > > work() > > finally: > > os.remove(fn) > > > > if __name__=='__main__': > > main() > > > > but it occurs to me that I might be killed with prejudice during the long > > running work(). Is there a smart way to avoid running simultaneously. > > Another method that you can use is to open up a socket on some > predetermined port (presumably above 1024), and then have your program > try to connect to that port and "talk" to the other program to > determine whether or not to run (or whether to do some of the > remaining work, etc.).
You don't need to talk to the socket, a second script trying to create a second socket on the same number will throw an exception and you can exit the script cleanly without running a second copy. You can also do this by holding a file open in write mode until the script has finished. try: open('lock.txt','w') my_script() except: #print script is already running If the file is already open the script won't run, if the script finshes/crashes or the machine reboots the open file will close. In both cases if the script finishes normally or crashes, or the machine is restarted. The lock (ie socket or open file) is released. HTH :) -- Tim Williams -- http://mail.python.org/mailman/listinfo/python-list