junjie 通过本文主要向大家介绍了python脚本编写实例,python脚本实例,python自动化脚本实例,python测试脚本实例,python入门脚本实例等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
保证只能运行一个脚本实例,方法是程序运行时监听一个特定端口,如果失败则说明已经有实例在跑。
使用装饰器实现,便于重用
import functools
def just_one_instance(func):
'''
</div>
装饰器
如果已经有实例在跑则退出
:return:
'''
@functools.wraps(func)
def f(*args,**kwargs):
import socket
try:
# 全局属性,否则变量会在方法退出后被销毁
global s
s = socket.socket()
host = socket.gethostname()
s.bind((host, 60123))
except:
print('already has an instance')
return None
return func(*args,**kwargs)
return f
[code]
在脚本的主函数上使用:
[code]
@just_one_instance
main():
do sth.
</div>

