singleton - Python: single instance of program - Stack Overflow

singleton - Python: single instance of program - Stack Overflow

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)

Update: the solutions offered are much more complex and less reliant than just having a port occupied with a non-existent server, so I'd have to go with that one.

link | edit | retag | flag

 upvote
 flag
Perhaps your life would be easier if you tracked down and fixed the segfault. Not that it's an easy thing to do. –  David Locke Dec 19 '08 at 15:53
 upvote
 flag
It's not in my library, it's in python's libxml bindings and extremely shy - fires only once a couple days. –  Slava N Dec 20 '08 at 17:51
2upvote
 flag
Python's standard library supports flock(), which is The Right Thing for modern UNIX programs. Opening a port uses a spot in a much more constrained namespace, whereas pidfiles are more complex as you need to check running processes to invalidate them safely; flock has neither problem. –  Charles Duffy Dec 20 '08 at 19:02
add comment

10 Answers

up vote 22 down vote accepted

The above 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

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

You can install tend using one of the following methods:

posted on 2012-04-24 10:28  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2012/04/24/2467630.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值