简体   繁体   English

检查Windows中是否已在运行Python脚本

[英]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? 为什么要检查Windows中是否已在运行特定的Python脚本,最好/最简单的方法是什么?

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. 我想确保在脚本启动时,没有另一个进程(同一脚本)已经在运行,因此我不会遇到试图移动相同文件的2个脚本的问题。

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. 我知道我可以使用psutil ,但是随后我将获得进程名称(python.exe),并且我在寻找为什么要区分Python进程是运行我的脚本还是其他程序。

You can use psutil.Process().cmdline() to see the complete command line of a process. 您可以使用psutil.Process().cmdline()查看进程的完整命令行。

Alternatively, you could lock the files you're working on. 或者,您可以锁定正在处理的文件。 See the answer to this question how to do this on ms-windows. 请参阅此问题的答案,如何在ms-windows上执行此操作。 The thing with locks is that you have to be careful to remove them, especially when an error occurs. 带锁的事情是,您必须小心删除它们,尤其是在发生错误时。

Use lockfile . 使用lockfile It is cross-platform, uses native OS functions and much more robust than any home-brewn lock file creation schemas 它是跨平台的,使用本机OS功能,并且比任何自制的锁定文件创建模式都更强大。

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 对于Windows操作系统,您可以使用timestamp.txt文件

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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