Note that there are some explanatory texts on larger screens.

plurals
  1. POpython - ensure script is activated only once
    primarykey
    data
    text
    <p>I'm writing a <code>Python 2.7</code> script.<br/> In summary, this script is being run every night on <code>Linux</code> and activates several processes.</p> <p>I'd like to ensure this script is not run multiple times in parallel (basically trying to mimic <code>Singleton</code> pattern but on application level) .</p> <p><em><strong>Code Example</em></strong></p> <pre><code>def main(): # before doing anything, I'd like to know whether this # script was activated and alive. # if so, error out # do something if __name__ == "__main__": main() </code></pre> <p><em><strong>Suggestion</em></strong></p> <p>The naive solution would be to create some kind of a lock file, that acts as a mutex.<br/> The first thing we do is to check whether this file exists. if so, then other instance of the script already created it and we should error out. when the script is done, we remove this file.<br/> I'm assuming this solution would work, as long as the operations on the file system are atomic. </p> <p><em><strong>Implementation</em></strong></p> <pre><code>import os, sys lock_file_path = ".lock_script" def lock_mutex(): if os.path.exists(lock_mutex_path): print "Error: script was already activated." sys.exit(-1) else: file = open(lock_mutex_path, 'w') def unlock_mutex(): assert( os.path.exists(lock_mutex_path)) os.remove(lock_mutex_path) def main(): try: lock_mutex() # do something unlock_mutex() except: unlock_mutex() if __name__ == "__main__": main() </code></pre> <p><em><strong>Problem</em></strong></p> <p>How to ensure <code>lock_mutex()</code> and <code>unlock_mutex()</code> are atomic?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload