簡體   English   中英

檢查Windows中是否已在運行Python腳本

[英]Check if a Python script is already running in Windows

為什么要檢查Windows中是否已在運行特定的Python腳本,最好/最簡單的方法是什么?

我有一個腳本,可以遍歷一個文件夾中的所有文件,並將它們復制到另一個文件夾(排序到“電影或電視節目”文件夾)。 我想確保在腳本啟動時,沒有另一個進程(同一腳本)已經在運行,因此我不會遇到試圖移動相同文件的2個腳本的問題。

我試圖在腳本的開頭創建一個文件,並在腳本完成時將其刪除,但是當腳本崩潰和/或引發錯誤時,我遇到了問題。

我知道我可以使用psutil ,但是隨后我將獲得進程名稱(python.exe),並且我在尋找為什么要區分Python進程是運行我的腳本還是其他程序。

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

或者,您可以鎖定正在處理的文件。 請參閱此問題的答案,如何在ms-windows上執行此操作。 帶鎖的事情是,您必須小心刪除它們,尤其是在發生錯誤時。

使用lockfile 它是跨平台的,使用本機OS功能,並且比任何自制的鎖定文件創建模式都更強大。

我已經通過使用一個空的虛擬文件解決了它。 在過程開始時,我檢查文件是否存在,如果不存在,則創建一個新文件,運行該過程並最后將其刪除(即使該過程失敗),如果該文件確實存在,則意味着該過程是現在運行,所以我終止了當前(新)進程。

對於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