2

i have a python script that can be runned in some seconds and some times it takes some minutes to be finished. im trying to make a script that prevents that my python code to run twice at same time

i tryed

print("python mycode.py" in (p.name() for p in psutil.process_iter()))

or

print("mycode.py" in (p.name() for p in psutil.process_iter()))

but its only works for linux how can i change it to work on linux and windows?

Jasar Orion
  • 626
  • 7
  • 26
  • some programs use file to inform other instance that script is already running. Script at start check if file exists. If exists then it doesn't run code. If file doesn't exists then it creates this file, run code and delete file at the end. Some program even put process ID in this file so other progran can use this ID to kill this process. – furas Apr 15 '20 at 00:41
  • 2
    [Make sure only a single instance of a program is running](https://stackoverflow.com/questions/380870/make-sure-only-a-single-instance-of-a-program-is-running) – furas Apr 15 '20 at 00:43
  • You generally do this with a named mutex or other named system object on Windows. The first instance of the process creates the mutex with a specific global name, the second attempts to create it, gets ERROR_ALREADY_EXISTS error and terminates. I can't think of a truly cross-platform way of doing it in python, though, and would like to hear a cross platform answer myself. – Boris Lipschitz Apr 15 '20 at 00:46

2 Answers2

3

thank you for help. i did with this code

from tendo import singleton
try:
    me = singleton.SingleInstance()
except:
    print("Already running")
    sys.exit(-1)
Jasar Orion
  • 626
  • 7
  • 26
0

My solution for this as tendo isn't reliable for me:

class runSingle:
def __init__(self, fileName) -> None:
    self.f = open(fileName, "w")
    self.f.close()
    try:
        os.remove(fileName)
        self.f = open(fileName, "w")
    except WindowsError:
        sys.exit()

a = runSingle("A")
 
Zain
  • 21
  • 2