Skip to content

Instantly share code, notes, and snippets.

import abc
class PluginBase(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self.base = 'base_info'
@abc.abstractmethod
def load(self, input):
@sapamja
sapamja / base_path.py
Last active August 29, 2015 14:03
getting basepath
base_path, _ = os.path.split(
os.path.dirname(os.path.realpath(__file__)
))
src = os.path.join(base_path, 'lib')
cfg = os.path.join(base_path, 'cfg')
@sapamja
sapamja / color_print.py
Created July 10, 2014 16:43
print color base on the level
class ColorScreen:
red = '\033[91m'
null = '\033[0m'
green = '\033[92m'
yellow = '\033[93m'
cyan = "\033[36m"
magenta = "\033[35m"
light_red = "\033[1;31m"
@sapamja
sapamja / partial.py
Created July 10, 2014 16:23
Use case for partial function:
from functools import partial
def log_template(level, message):
print("{}: {}".format(level, message))
log_info = partial(log_template, "info")
log_warning = partial(log_template, "warning")
log_error = partial(log_template, "error")
>>> log_info("test test test 1 2 3")
@sapamja
sapamja / commands.py
Created July 8, 2014 03:54
class to execute shell cmd
class Command(object):
def __init__(self, args):
self.cmd_args = args
def __call__(self):
(self.out, self.err) = subprocess.Popen(self.cmd_args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True).communicate()
@sapamja
sapamja / option_parser.py
Created July 8, 2014 03:19
option_parser with Required
import optparse
# http://code.activestate.com/recipes/573441-extended-optparse-to-allow-definition-of-required-/
strREQUIRED = 'required'
class OptionWithDefault(optparse.Option):
ATTRS = optparse.Option.ATTRS + [strREQUIRED]
def __init__(self, *opts, **attrs):
@sapamja
sapamja / print_dump.py
Created June 9, 2014 22:43
print_dump
def pp(json_docs):
"""preety print for json docs"""
print json.dumps(json_docs, indent=4)
def get_md5(key):
"""return md5 hex for key"""
md5 = hashlib.md5()
md5.update(key)
return md5.hexdigest()
@sapamja
sapamja / yes_no_input.py
Created June 9, 2014 22:42
yes_no_input
def yes_no(arg):
"""get input yes or no"""
print '%s [y|n]:' % arg,
if str(raw_input()).lower() == 'y':
return True
print 'Oops exiting!'
return False
def get_input(msg=None, password=False):
@sapamja
sapamja / key_in_dict
Created June 6, 2014 16:48
Check multiple key exists in dictionary
>>> dic = { 1 : 'a', 2: 'b' }
>>> set(dic)
set([1, 2])
# Check if any key exists:
>>> set([1,2]) <= set(dic)
True
>>> set([1]) <= set(dic)
@sapamja
sapamja / concantenate_string_timeit.py
Last active August 29, 2015 14:00
Fastest way to concatenate string in python
#!/usr/bin/python
import cProfile
from faker import Faker
from timeit import Timer
from UserString import MutableString
from cStringIO import StringIO
#from memory_profiler import profile
def func1(List):
"""Naive appending"""