Skip to content

Instantly share code, notes, and snippets.

@saml

saml/selfdb.py

Created Dec 15, 2012
Embed
What would you like to do?
# -*- coding: utf-8 -*-
# seq 5000 | xargs -P100 -I% python2 selfdb.py k% v%
'''{prog} -- self-logging in-memory key-value storage
Usage:
Display Keys
{prog}
Get Value of Key
{prog} some-key
Set Value of Key
{prog} some-key some-value
Remove Key
{prog} some-key ""
'''
import atexit
import sys
import logging
import os
__doc__ = __doc__.format(prog=os.path.basename(__file__))
DB = {}
logging.basicConfig(filename=__file__, format='%(message)s')
def main():
args = sys.argv[1:]
argc = len(args)
if argc < 1:
print(DB.keys())
elif argc < 2:
key = args[0]
if key == '-h':
print(__doc__)
else:
val = DB.get(key, None)
print('%s = %s' % (key, val))
else:
key = args[0]
val = args[1]
if val:
logging.error('DB[%s]=%s' % (repr(key), repr(val)))
else:
logging.error('DB.pop(%s,None)' % repr(key))
atexit.register(main)
#DB LOG
@lecram

This comment has been minimized.

Copy link

@lecram lecram commented Dec 18, 2012

Pretty nice! I like the atexit trick. The downside of this approach is all the DB.pop() calls (and possibly redundant assignments) that will appear if one removes keys (and redefines then) frequently.

@apg

This comment has been minimized.

Copy link

@apg apg commented Apr 15, 2013

@lecram but you could just have another operation that "compresses" the log and spits it back out. I guess you'd have to lock the entire database to do that reliably though...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.