简体   繁体   中英

Check if a Python script is already running in Windows

What is the best/easiest why to check if a specific Python script already running in Windows?

I have a script that goes over all files in a folder and copies them to another folder (sort to Movie or TV Shows folder). I want to make sure when the script starts that there isn't another process (of the same script) that is already running, so I wouldn't have issues with 2 scripts that are trying to move the same files.

I have tried to create a file in the start of the script and deleting it when the script finishes, but I got into problems when the script crashes and/or throws an error.

I know that I can use psutil , but then I will get the process name (python.exe) and I'm looking for a why to distinguish if the Python process is running my script or another program.

You can use psutil.Process().cmdline() to see the complete command line of a process.

Alternatively, you could lock the files you're working on. See the answer to this question how to do this on ms-windows. The thing with locks is that you have to be careful to remove them, especially when an error occurs.

Use lockfile . It is cross-platform, uses native OS functions and much more robust than any home-brewn lock file creation schemas

I have solved it by using an empty dummy file. At the start of the process I check if the file exists, if not I create a new file, run the process and delete it in the end (even if the process failed), if the file does exist, that means that the process is running now so I terminate the current (new) process.

For Windows os you can use timestamp.txt file

timestamp = 'timestamp.txt'
...
elif windows:
    try:
        new_timestamp = False
        if not os.path.exists(timestamp):
            new_timestamp = True
            try:
                with open(timestamp, 'a') as f_timestamp:
                    f_timestamp.write(str(int_t0))
            except IOError as e:
                out1 = 'M. Cannot open file for writing. Error: %s - %s.' \
                           % (e.logfile, e.strerror) + ' -> Exit code 3'
                logging.error(out1)
                sys.exit(3)

        if not new_timestamp and os.path.exists(timestamp):
            out1 = 'N. Script ' + __file__ + ' is already running.'
            print(out1)
            logging.error(out1)
            sys.exit(0)

    except IOError as e:
        out1 = 'J. Cannot open file. Error: %s - %s.' \
           % (e.filepath, e.strerror)  + ' -> Exit code 4'
        logging.error(out1)

...
try:
    f_timestamp.close()
    os.remove(timestamp)
except OSError as e:
    logging.error('B. Cannot delete ' + timestamp + \
          ' Error: %s - %s.' % (e.filename, e.strerror))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM