确保仅单个程序实例在运行 [英] Make sure only a single instance of a program is running

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

问题描述

有没有一种Python方式可以只运行一个程序实例?

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?

(考虑到程序有时可能会失败,即segfault-因此锁定文件"之类的东西将无法工作)

(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:

  • easy_install tendo
  • pip install tendo
  • manually by getting it from http://pypi.python.org/pypi/tendo

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

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