allow only one instance of python script? [duplicate]

  • Last Update :
  • Techknowledgy :

The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.

from tendo
import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running

Simple, cross-platform solution, found in another question by zgoda:

import fcntl
import os
import sys

def instance_already_running(label = "default"):
if an an instance with the label is already running, globally
at the operating system level.

Using ``
ensures that the file pointer won 't be closed
by Python 's garbage collector after the function'
s scope is exited.

The lock will be released when the program exits, or could be
if the file pointer were closed.

lock_file_pointer = "/tmp/instance_{label}.lock", os.O_WRONLY)

fcntl.lockf(lock_file_pointer, fcntl.LOCK_EX | fcntl.LOCK_NB)
already_running = False
except IOError:
   already_running = True

return already_running

This code is Linux specific. It uses 'abstract' UNIX domain sockets, but it is simple and won't leave stale lock files around. I prefer it to the solution above because it doesn't require a specially reserved TCP port.

import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# # Create an abstract socket, by prefixing it with null.
except socket.error as e:
   error_code = e.args[0]
error_string = e.args[1]
print "Process already running (%d:%s ). Exiting" % (error_code, error_string)

Never written python before, but this is what I've just implemented in mycheckpoint, to prevent it being started twice or more by crond:

import os
import sys
import fcntl
fh = 0
def run_once():
   global fh
fh = open(os.path.realpath(__file__), 'r')
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)


Use a pid file. You have some known location, "/path/to/pidfile" and at startup you do something like this (partially pseudocode because I'm pre-coffee and don't want to work all that hard):

import os, os.path
pidfilePath = """/path/to/pidfile"""
if os.path.exists(pidfilePath):
pidfile = open(pidfilePath,"r")
pidString =
if <pidString is equal to os.getpid()>:
   # something is real weird
   <use ps or pidof to see if the process with pid pidString is still running>
      if <process with pid=='pidString' is still running>:
         # the previous server must have crashed
         <log server had crashed>
            <reopen pidfilePath for writing>
               <open pidfilePath for writing>

The best solution for this on windows is to use mutexes as suggested by @zgoda.

import win32event
import win32api
from winerror

mutex = win32event.CreateMutex(None, False, 'name')
last_error = win32api.GetLastError()

if last_error == ERROR_ALREADY_EXISTS:
   print("App instance already running")

Suggestion : 2

Post date April 16, 2022 ,© 2022 The Web Dev

We install it by running

pip install tendo

Then we write

from tendo
import singleton

me = singleton.SingleInstance()

Suggestion : 3

Enum class decorator that ensures only one name is bound to any one value.,Instances are replaced with an appropriate value for Enum members. By default, the initial value starts at 1.,A class decorator specifically for enumerations. It searches an enumeration’s __members__ gathering any aliases it finds; if any are found ValueError is raised with the details:,By default, enumerations allow multiple names as aliases for the same value. When this behavior isn’t desired, the following decorator can be used to ensure each value is used only once in the enumeration:

>>> from enum
import Enum
   class Color(Enum):
   ...RED = 1
   ...GREEN = 2
   ...BLUE = 3
>>> print(Color.RED)
>>> print(repr(Color.RED))
<Color.RED: 1>
>>> type(Color.RED)
<enum 'Color'>
   >>> isinstance(Color.GREEN, Color)
>>> print(
>>> class Shake(Enum):
   ...VANILLA = 7
   ...CHOCOLATE = 4
   ...COOKIES = 9
   ...MINT = 3
   for shake in Shake:

Suggestion : 4

Last Updated : 30 May, 2022


Input: [2, 4, 10, 20, 5, 2, 20, 4]
Output: [2, 4, 10, 20, 5]

Input: [28, 42, 28, 16, 90, 42, 42, 28]
Output: [28, 42, 16, 90]


[2, 4, 10, 20, 5]


[2, 4, 10, 20, 5]

[1, 2, 6, 5, 3, 7, 8]

Suggestion : 5

By default, cloud-init allows only one content type in user data at a time. However, this example shows both text/cloud-config and text/x-shellscript content-types in a mime-multi part file. ,The text/cloud-config content type overrides how frequently user data is run in the cloud-init package by setting the SCRIPTS-USER parameter to ALWAYS.,The text/x-shellscript content type provides the actual user script to be run by the cloud-init cloud_final_modules module. In this example, there is only one line to be run, which is /bin/echo "Hello World." >> /tmp/testfile.txt.,I want to utilize user data to run a script every time my Amazon Elastic Compute Cloud (Amazon EC2) instance is restarted. How can I do that?

Content - Type: multipart / mixed;
boundary = "//"
MIME - Version: 1.0

   -- //
Content - Type: text / cloud - config;
charset = "us-ascii"
MIME - Version: 1.0
Content - Transfer - Encoding: 7 bit
Content - Disposition: attachment;
filename = "cloud-config.txt"

#cloud - config
   -[scripts - user, always]

   -- //
Content - Type: text / x - shellscript;
charset = "us-ascii"
MIME - Version: 1.0
Content - Transfer - Encoding: 7 bit
Content - Disposition: attachment;
filename = "userdata.txt"

#!/bin/bash /
   bin / echo "Hello World" >> /tmp/testfile.txt
   -- //--