1

I have a python script called speech.pyw. I don't want it showing up on the screen when run so I used that extension.

How can I check using another python script whether or not this script is running? If it isn't running, this script should launch it.

1
  • If it's just Windows you should use the object namespace, e.g. a named section of shared memory that has the PID, e.g. m = mmap.mmap(-1, 8, 'Global\\Spam'); pid = int.from_bytes(m, 'little'). If pid is non-zero it can exit. Otherwise the script writes its pid to the shared memory, e.g. m[:] = os.getpid().to_bytes(8, 'little'), and continues to execute. The latter uses the name 'Global\\Spam', which is a section named "Spam" that's globally visible across all Windows sessions. If you want it to be for the current session only, use 'Spam' or 'Local\\Spam'. Commented Jul 30, 2017 at 23:17

2 Answers 2

1

Off the top of my head, there are at least two ways to do this:

  • You could make the script create an empty file in a specific location, and the other script could check for that. Note that you might have to manually remove the file if the script exits uncleanly.
  • You could list all running processes, and check if the first one is among those processes. This is somewhat more brittle and platform-dependant.

An alternative hybrid strategy would be for the script to create the specific file and write it's PID (process id) to it. The runner script could read that file, and if the specified PID either wasn't running or was not the script, it could delete the file. This is also somewhat platform-dependant.

Sign up to request clarification or add additional context in comments.

1 Comment

For Windows, use os.open with the flag O_TEMPORARY to get a file that's guaranteed to be removed when the process exits, even if the process is terminated. If you want the file to be per-session, you'll have to name the file including the current session ID. It's better to use a named section of shared memory because you get all of this automatically -- i.e. cleanup and per-session namespace.
0
!/usr/bin/env python2
import psutil
import sys

processName="wastetime.py"

def check_if_script_is_running(script_name):
    script_name_lower = script_name.lower()
    for proc in psutil.process_iter():
        try:
            for element in proc.cmdline():
                if element.lower() == script_name_lower:
                    return True
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    return False;

print(check_if_script_is_running(processName))
sys.stdin.readline()

1 Comment

pip install psutil ... This gives you access to lots of information about your machine,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.