Home  >  Article  >  Backend Development  >  Python实现保证只能运行一个脚本实例

Python实现保证只能运行一个脚本实例

WBOY
WBOYOriginal
2016-06-10 15:10:191110browse

保证只能运行一个脚本实例,方法是程序运行时监听一个特定端口,如果失败则说明已经有实例在跑。

使用装饰器实现,便于重用

复制代码 代码如下:

import functools
def just_one_instance(func):

'''


装饰器

如果已经有实例在跑则退出

复制代码 代码如下:

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn