有没有一种Pythonic式的方法让一个程序只运行一个实例?
我想出的唯一合理的解决方案是尝试将其作为服务器在某个端口上运行,然后第二个程序尝试绑定到相同的端口-失败。但这真的不是一个好主意,也许有比这更轻量级的东西?
(考虑到程序有时会失败,也就是段错误-所以像"lock file“这样的东西不会工作)
发布于 2009-08-12 10:45:25
下面的代码可以完成这项工作,它是跨平台的,可以在Python2.4-3.2上运行。我在Windows、OS X和Linux上测试了它。
from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running
提供了最新的代码版本
singleton.py
..。请
这里有文件错误
..。
您可以使用以下方法之一安装tend:
通过从以下位置获取它来手动执行此操作
http://pypi.python.org/pypi/tendo
发布于 2008-12-21 14:02:47
简单,
跨平台
解决方案,可在
另一个问题
由
zgoda
import fcntl
import os
import sys
def instance_already_running(label="default"):
"""
Detect if an an instance with the label is already running, globally
at the operating system level.
Using `os.open` ensures that the file pointer won't be closed
by Python's garbage collector after the function's scope is exited.
The lock will be released when the program exits, or could be
released if the file pointer were closed.
"""
lock_file_pointer = os.open(f"/tmp/instance_{label}.lock", os.O_WRONLY)
try:
fcntl.lockf(lock_file_pointer, fcntl.LOCK_EX | fcntl.LOCK_NB)
already_running = False
except IOError:
already_running = True
return already_running
很像S.Lott的建议,但代码。
发布于 2009-11-03 01:10:48
这段代码是特定于Linux的。它使用“抽象的”UNIX域套接字,但它很简单,不会留下陈旧的锁文件。我更喜欢上面的解决方案,因为它不需要特别保留的TCP端口。
try:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
## Create an abstract socket, by prefixing it with null.
s.bind( '\0postconnect_gateway_notify_lock')
except socket.error as e:
error_code = e.args[0]
error_string = e.args[1]
print "Process already running (%d:%s ). Exiting" % ( error_code, error_string)
sys.exit (0)
唯一的字符串
可以更改为允许需要实施单个实例的多个程序。
https://stackoverflow.com/questions/380870
复制相似问题