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

2024-09-28 22:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

检查特定Python脚本是否已经在Windows中运行的最佳/最简单的原因是什么?在

我有一个脚本,可以遍历文件夹中的所有文件,并将它们复制到另一个文件夹(排序到电影或电视节目文件夹)。 我想确保当脚本启动时没有另一个进程(同一个脚本的)正在运行,这样我就不会有两个脚本试图移动相同文件的问题。在

我试图在脚本的开头创建一个文件,并在脚本完成时删除它,但是当脚本崩溃和/或抛出错误时,我遇到了问题。在

我知道我可以使用psutil,但是我会得到进程名(python.exe)我在寻找一个原因来区分Python进程是运行我的脚本还是其他程序。在


Tags: 文件程序脚本文件夹电影排序进程windows
3条回答

对于Windows操作系统,您可以使用时间戳.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))

您可以使用psutil.Process().cmdline()查看进程的完整命令行。在

或者,您可以锁定正在处理的文件。请参阅this question如何在ms windows上执行此操作的答案。锁的问题是你必须小心地移除它们,尤其是当发生错误时。在

使用lockfile。它是跨平台的,使用本机操作系统功能,比任何home-brewn锁文件创建模式更健壮

相关问题 更多 >