Skip to content

Instantly share code, notes, and snippets.

@danilin-em
Last active November 24, 2019 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilin-em/dada991df582b40762664430cccb3ab5 to your computer and use it in GitHub Desktop.
Save danilin-em/dada991df582b40762664430cccb3ab5 to your computer and use it in GitHub Desktop.
Using /dev/shm as Storage
""" Saving Value in to /dev/shm
See: https://gerardnico.com/os/linux/shared_memory
Usage:
myapp.py
-----------------------------------------
ds = DevShm('myapp')
idx = int(ds.get('index', 0))
print('My App index:', idx)
idx += 1
ds.set('index', idx)
-----------------------------------------
$ python3 myapp.py
My App index: 0
$ python3 myapp.py
My App index: 1
$ python3 myapp.py
My App index: 2
...
"""
class DevShm:
""" Manager /dev/shm """
__namespace = None
__filepath = None
def __init__(self, namespace=__file__):
self.__set_namespace(str(namespace))
def __set_namespace(self, namespace):
self.__namespace = namespace.replace('.', '-').replace('/', '-').replace(' ', '_').replace('\\', '-')
self.__set_filepath()
return self.__namespace
def get_namespace(self):
return self.__namespace
def __set_filepath(self):
self.__filepath = '/dev/shm/%s' % str(self.__namespace)
return self.__filepath
def get_filepath(self):
return self.__filepath
def set(self, name, value=None):
""" Set Value """
with open(self.__filepath+'-'+name, 'w+') as f:
f.write(str(value))
return value
def get(self, name, default=None):
""" Get Value """
value = default
try:
with open(self.__filepath+'-'+name, 'r') as f:
value = f.read()
except FileNotFoundError as e:
self.set(name, value)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment