Skip to content

Instantly share code, notes, and snippets.

@billiepander
Last active April 21, 2017 05:47
Show Gist options
  • Select an option

  • Save billiepander/f5c67fab742f50aa6b69a9653c223f11 to your computer and use it in GitHub Desktop.

Select an option

Save billiepander/f5c67fab742f50aa6b69a9653c223f11 to your computer and use it in GitHub Desktop.
1: Take care, as kill -9 will drop the python interpreter immediately, so if -9 happens, no way to clean up; 2. you may wonder why not use try: ... finally: ... to do cleanup, cause finally block will only get executed when inner exception happens, that means outer like kill $PID wont trigger it too, which is often used
import os
import signal
import time
import requests
from functools import partial
from redis import Redis
redis_conn = Redis(host='xxx', port=xxxx, password='xxxx')
def ini_life():
# write initial here
resp = requests.get('http://httpbin.org/ip').json()
ip = resp.get('origin')
if not redis_conn.sismember('xxxs_set', ip):
redis_conn.lpush('xxxs_list', ip)
redis_conn.sadd('xxxs_set', ip)
return ip
def exit_life(signum, stack, ip):
# write cleanup code here
# ip is extra params, later use partial to hide it
redis_conn.lrem('xxxs_list', ip)
redis_conn.srem('xxxs_set', ip)
os._exit(0)
def track_life(func):
def inner(*args, **kwargs):
ip = ini_life()
leave_life = partial(exit_life, ip=ip)
signal.signal(signal.SIGABRT, leave_life) # kill -6 $PID
signal.signal(signal.SIGTERM, leave_life) # kill $PID (-15)
func(*args, **kwargs)
return inner
@track_life
def main():
while True:
time.sleep(15)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment