Home > Software design >  How to check if python file is already running?
How to check if python file is already running?

Time:09-16

I am working on client-server project using Tkinter GUI, and I want to check if ChatServer.py is running before I am running ChatClient.py file.

for example:

I want to run the Client().runGUI() line only if ChatServer.py is running, else I want to print an message to the terminal.

def runGUI(self):
   self.window.mainloop()


Client().runGUI()

I have no access to the server, so I cant check if is running or not, my main question is if I can run a line of code only if ChatServer.py is already running.

Pic of my current python files

CodePudding user response:

This answer assumes the server and the client are running on the same machine. An easy approach is to create a lock file. Basically, the server creates the file when it is run, then deletes the file when it ends. This way, one can always know if the process is running. Here's an example of what the server should do:

import atexit
import os
import tempfile
import sys

# Create the file. If it already exists (the server is already running), then
# this fails and the program stops here.
lock = open(tempfile.gettempdir()   '/chatserver.lock', 'x')
lock.close()


# Function to delete the lock.
def removeLock():
    os.remove(tempfile.gettempdir()   '/chatserver.lock')


atexit.register(removeLock)

#
# Main server code
#

# Put this at the end of the program, or whatever code is run when the program
# is about to end.
removeLock()

Then, in the client all you have to do is check if the file exists. Like this:

import os
import tempfile

if os.path.exists(tempfile.gettempdir()   '/chatserver.lock'):
    # do stuff
  • Related