网络编程
位置:首页>> 网络编程>> Python编程>> Python实现保证只能运行一个脚本实例

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

作者:junjie  发布时间:2021-04-01 06:58:39 

标签:Python,保证,一个脚本

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

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


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.

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com