在Windows中操作系统下,检查Python脚本是否已运行

作者:虚坏叔叔

早餐店不会开到晚上,想吃的人早就来了!😄

python判断程序是否在进程中 怎么判断python有没有在跑_python判断程序是否在进程中

一、原理

用一个空的虚拟文件。

在进程开始时,检查文件是否存在,如果不存在,就创建一个新文件,运行该进程并最终将文件删除(即使进程失败),如果文件确实存在,则意味着该进程是正在运行,所以我终止当前(新)进程。

二、完整代码

通过判断timestamp.txt是否存在

if not os.path.exists(timestamp)

如果在运行就停止当前脚本

if IsRunning():
    sys.exit(0)
else:
    print("执行业务代码")
import os
import logging
import sys

timestamp = 'timestamp.txt'

def IsRunning():
    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(1))
            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)
            return True

    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))
        return True
    return False

if IsRunning():
    sys.exit(0)
else:
    print("执行业务代码")

运行结果如下

当这个文件不存在 就可以执行业务代码

python判断程序是否在进程中 怎么判断python有没有在跑_开发语言_02

如果文件存在 则退出脚本的执行

python判断程序是否在进程中 怎么判断python有没有在跑_python_03

三、通过mutex

通过赵4老师的评论 发现他的方案更好

import win32event,win32api
import time
import sys
if __name__ == '__main__':
    mutex = win32event.CreateMutex(None, False, 'program_name')
    if win32api.GetLastError() > 0:
        print('程序已运行...')
        sys.exit(0)
    while True:
        time.sleep(1)
        print("running")

代码如上

可以看到 当运行一个脚本。 此时会一直运行

python判断程序是否在进程中 怎么判断python有没有在跑_python_04

再次运行脚本 ,程序会正常退出

python判断程序是否在进程中 怎么判断python有没有在跑_QT_05

而且不同的Python脚本间不会有影响

总结

最后的最后
由本人水平所限,难免有错误以及不足之处, 屏幕前的靓仔靓女们 如有发现,恳请指出!

最后,谢谢你看到这里,谢谢你认真对待我的努力,希望这篇博客对你有所帮助!