Skip to content

Instantly share code, notes, and snippets.

@saml
Created December 15, 2012 06:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saml/4291690 to your computer and use it in GitHub Desktop.
Save saml/4291690 to your computer and use it in GitHub Desktop.
# -*- 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
Copy link

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
Copy link

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