确保只有一个程序实例正在运行 [英] Make sure only a single instance of a program is running

查看:33
本文介绍了确保只有一个程序实例正在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种 Pythonic 的方式让一个程序只运行一个实例?

Is there a Pythonic way to have only one instance of a program running?

我想出的唯一合理的解决方案是尝试在某个端口上将其作为服务器运行,然后第二个程序尝试绑定到同一端口 - 失败.但这并不是一个好主意,也许还有比这更轻巧的东西?

The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?

(考虑到程序有时会失败,即段错误 - 所以锁定文件"之类的东西将不起作用)

(Take into consideration that program is expected to fail sometimes, i.e. segfault - so things like "lock file" won't work)

推荐答案

以下代码应该可以完成这项工作,它是跨平台的并且可以在 Python 2.4-3.2 上运行.我在 Windows、OS X 和 Linux 上进行了测试.

The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.

from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running

最新的代码版本在 singleton.py 可用.请在此处提交错误.

The latest code version is available singleton.py. Please file bugs here.

您可以使用以下方法之一安装tend:

You can install tend using one of the following methods:

这篇关于确保只有一个程序实例正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆