只允许1个python脚本实例[重复]

时间:2022-05-21 07:34:24

Possible Duplicate:
Python: single instance of program

可能重复:Python:程序的单个实例

What is the best way to insure that only 1 copy of a python script is running? I am having trouble with python zombies. I tired creating a write lock using open("lock","w"), but python doesn't notify me if the file already has a write lock, it just seems to wait.

确保只运行一个python脚本的最佳方法是什么?我遇到了python僵尸的麻烦。我厌倦了使用open(“lock”,“w”)创建一个写锁,但如果文件已经有写锁,python不通知我,它似乎只是等待。

2 个解决方案

#1


3  

Try:

import os
os.open("lock", os.O_CREAT|os.O_EXCL)

The documentation for os.open and its flags.

os.open及其标志的文档。

#2


1  

Your question is similar to this one: What is the best way to open a file for exclusive access in Python?. The answers given there should help you with your issue.

您的问题与此类似:在Python中打开文件进行独占访问的最佳方法是什么?那里给出的答案应该可以帮助您解决问题。

(Use the flag combination portalocker.LOCK_EX!|portalocker.LOCK_NB to return quickly. If the file is locked by another process, your script should get an exception.)

(使用标志组合portalocker.LOCK_EX!| portalocker.LOCK_NB快速返回。如果文件被另一个进程锁定,则您的脚本应该获得异常。)

#1


3  

Try:

import os
os.open("lock", os.O_CREAT|os.O_EXCL)

The documentation for os.open and its flags.

os.open及其标志的文档。

#2


1  

Your question is similar to this one: What is the best way to open a file for exclusive access in Python?. The answers given there should help you with your issue.

您的问题与此类似:在Python中打开文件进行独占访问的最佳方法是什么?那里给出的答案应该可以帮助您解决问题。

(Use the flag combination portalocker.LOCK_EX!|portalocker.LOCK_NB to return quickly. If the file is locked by another process, your script should get an exception.)

(使用标志组合portalocker.LOCK_EX!| portalocker.LOCK_NB快速返回。如果文件被另一个进程锁定,则您的脚本应该获得异常。)