def __init__(self,filename): MODULE().Import('import sqlite3') self.filename=filename self.conn=None self.cur=None self.Conn() self.Cur()
# Kage Park from klib.MODULE import * MODULE().Import('from klib.Get import Get') def Crc( rt, chk='_', rc={ 'GOOD': [True, 'True', 'Good', 'Ok', 'Pass', {'OK'}, 0], 'FAIL': [False, 'False', 'Fail', {'FAL'}, 1], 'NONE': [None, 'None', 'N/A', {'NA'}], 'IGNO': ['IGNO', 'Ignore', {'IGN'}], 'ERRO': ['ERR', 'Error', {'ERR'}, -1], 'WARN': ['Warn', {'WAR'}], 'UNKN': ['Unknown', 'UNKN', {'UNK'}], 'JUMP': ['Jump', {'JUMP'}] }, rt_true=True, rt_false=False): def Trans(irt): type_irt = type(irt) for ii in rc: for jj in rc[ii]: if type(jj) == type_irt and ( (type_irt is str and jj.lower() == irt.lower()) or jj == irt): return ii return 'UNKN'
#Kage Park from distutils.spawn import find_executable import os import fnmatch from klib.MODULE import * MODULE().Import('from klib.CONVERT import CONVERT') MODULE().Import('import magic') MODULE().Import('import tarfile') MODULE().Import('import zipfile') class FILE: def __init__(self, src): self.src = src def Info(self, filename=None, default={}, data=False): if filename is None: filename = self.src rt = {} if isinstance(filename, str) and os.path.isfile(filename): rt['path'] = os.path.dirname(filename) filename_info = os.path.basename(filename).split('.') rt['filename'] = filename_info if 'tar' in filename_info: idx = filename_info.index('tar') else: idx = -1 rt['name'] = '.'.join(filename_info[:idx]) rt['ext'] = '.'.join(filename_info[idx:]) aa = magic.from_buffer(open(filename, 'rb').read(2048)) if aa:
import os import pickle import sys import inspect from klib.MODULE import * MODULE().Import('from klib.Type import Type') MODULE().Import('from klib.FILE import FILE') MODULE().Import('from klib.OutFormat import OutFormat') MODULE().Import('from klib.Abs import Abs') class GET: def __init__(self, src=None, **opts): self.src = src def __repr__(self): if self.src is None: return repr(self.MyAddr()) if Type(self.src, ('instance', 'classobj')): def method_in_class(class_name): ret = dir(class_name) if hasattr(class_name, '__bases__'): for base in class_name.__bases__: ret = ret + method_in_class(base) return repr(ret) return repr(method_in_class(self.src)) elif Type(self.src, 'dict'): return repr(list(self.src.keys())) elif Type(self.src, ('str', 'list', 'tuple')): return repr(len(self.src))
#Kage Park import re from klib.MODULE import * MODULE().Import('from klib.Abs import Abs') MODULE().Import('from klib.Misc import *') class LIST(list): def __init__(self, *inps): if len(inps) == 1 and isinstance(inps[0], (list, tuple)): self.root = list(inps[0]) else: self.root = list(inps) # def __new__(cls,*inps): # if len(inps) == 1 and isinstance(inps[0],(list,tuple)): # return list(inps[0]) # else: # return list(inps) # reply self.root back to the Class's output a=List(['a']), return the data to a def __repr__(self): return repr(self.root) def Convert(self, src, path=False, default=False, symbol=':white_space:', **opts):
#Kage Park import os import setuptools from klib.MODULE import * MODULE().Import('klib.SHELL import SHELL') def lib_ver(): gver = SHELL().Run( '''git describe --tags | sed "s/^v//g" | sed "s/^V//g"''') if gver[0] == 0: return gver[1] return '2.0' long_description = '' if os.path.isfile('README.md'): with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name='klib', version='{}'.format(lib_ver()), # scripts=['klib'], author='Kage Park', #autor_email='', description='Enginering useful library', long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/kagepark/klib",
#Kage park import sys import subprocess from threading import Thread from klib.MODULE import * MODULE().Import('from klib.TIME import TIME') class SHELL: def __init__(self): pass def Pprog(self, stop, progress_pre_new_line=False, progress_post_new_line=False, log=None, progress_interval=5): TIME().Sleep(progress_interval) if stop(): return if progress_pre_new_line: if log: log('\n', direct=True, log_level=1) else: sys.stdout.write('\n') sys.stdout.flush() post_chk = False while True: if stop(): break
def __init__(self): MODULE().Import('import mysql')
#Kage Park """ Based on Python2.7 and Python3.x's types module Inhance for make sure """ import sys, os from klib.MODULE import * MODULE().Import('magic') def ObjName(obj, default=None): if isinstance(obj, str): if os.path.isfile(obj): aa = magic.from_buffer(open(obj, 'rb').read(2048)) if aa: return aa.split()[0].lower() try: with open(obj, 'rb') as f: # Pickle Type pickle.load(f) return 'pickle' except: pass return 'str' else: obj_dir = dir(obj) obj_name = type(obj).__name__ if obj_name in ['function']: return obj_name if '__dict__' in obj_dir: if obj_name == 'type': return 'classobj' return 'instance' # elif obj_name == 'type': # return obj.__name__
#Kage park import pickle import multiprocessing import fcntl, socket, struct from klib.MODULE import * MODULE().Import('from klib.Type import Type') MODULE().Import('ssl') def _u_bytes(val, encode='utf-8'): if Py3(): if type(val) is bytes: return val else: return bytes(val, encode) return bytes(val) # if change to decode then network packet broken #return val.decode(encode) def _u_str2int(val, encode='utf-8'): if Py3: if type(val) is bytes: return int(val.hex(), 16) else: return int(_u_bytes(val, encode=encode).hex(), 16) return int(val.encode('hex'), 16) def _dict(pk={}, add=False, **var): for key in var.keys(): if key in pk:
import os import sys sys.path.append( '/'.join(os.path.dirname(os.path.abspath(__file__)).split('/')[:-2]) + '/klib') from klib.MODULE import * MODULE().Import('klib.STR import STR') aa = '''App.py:from distutils.spawn import find_executabledeg IPMICfg.py:from distutils.spawn import find_executable kBmc.py:from distutils.spawn X11 import find_executable kBmc.py:from disTutils. spawn X11abc import find_executable kBmc.py: if find_executable('ipmitool') is False: kmisc.py:from distutils.spawn X113 import from find_executable kmisc.py: if find_executable('ping'): kmisc.py: if find_executable('ping'): misc.py adf widk lsu Nutanix.py:from distutils.spawn X121 import find_executable SMCIPMITool.py:from dist X12iTU utils.spawn import find_executable SumEFI.py:from distutils.spawn import find_executable Sum.py:from distutils.spawn import find_executable''' print(STR(aa).Find('(\w*exec*)', findall=True)) print(STR(aa).Index('from')) print(STR(aa).Index('from', findall=True)) print(STR(aa).Find('from (\w*).spawn', pattern=True, findall=True)) print(STR(aa).Index('from (\w*).spawn', pattern=True)) print(STR(aa).Find('from (\w*).spawn', pattern=True)) print(STR(aa).Index('from (\w*).spawn', pattern=True, findall=True)) print(STR(aa).Find('X(\d*)[a-zA-Z]', findall=True))
# Kage Park import json as _json import pickle #import inspect from sys import modules from distutils.spawn import find_executable from klib.MODULE import * MODULE().Import('from klib.IP import IP') MODULE().Import( 'from klib.Misc import *' ) # import kmisc(file)'s each function to local module's function MODULE().Import('from klib.Type import Type') MODULE().Import('from klib.MAC import MAC') MODULE().Import('from klib.GET import GET') class IS: def __init__(self, src=None, **opts): self.src = src self.rtd = opts.get( 'rtd', { 'GOOD': [True, 'True', 'Good', 'Ok', 'Pass', {'OK'}, 0], 'FAIL': [False, 'False', 'Fail', {'FAL'}], 'NONE': [None, 'None', 'N/A', {'NA'}], 'IGNO': ['IGNO', 'Ignore', {'IGN'}], 'ERRO': ['ERR', 'Error', {'ERR'}], 'WARN': ['Warn', {'WAR'}], 'UNKN': ['Unknown', 'UNKN', {'UNK'}], 'JUMP': ['Jump', {'JUMP'}] })
import os import sys sys.path.append( '/'.join(os.path.dirname(os.path.abspath(__file__)).split('/')[:-2]) + '/klib') from klib.MODULE import * MODULE().Import('klib.DICT import DICT') test = { 'a': 123, 'b': { 'c': {'ddd'}, 'e': {}, 'z': 123, } } root = DICT(test) print('** base:') root.Print() print('** Add tree/apple:') root.Mk('tree.apple') root.Print() print('** tree/apple/color = red') root.tree.apple.color = 'red' print('** get tree/apple/color:', root.tree.apple.color.Get()) print('** put white-red to tree/apple/color') root.tree.apple.Put('color', 'white-red') print('** get tree/apple/color:', root.tree.apple.color.Get())
import os import sys sys.path.append( '/'.join(os.path.dirname(os.path.abspath(__file__)).split('/')[:-2]) + '/klib') from klib.MODULE import * MODULE().Import('klib.LIST import LIST') l = LIST(1) print(l, type(l)) l.Append(2) print('l:', l) print(tuple(l.Get())) l.Get().append(3) print(l) print(l.Get(-1)) print(l.Get(-9)) l.Insert('I', 'I2', at=2) print(l) l.Insert('E', 'E2', at=-0) print(l) l.Append('A', 'A2') print(l)
#Kage Park import random import re from klib.MODULE import * MODULE().Import('klib.OutFormat import OutFormat') class STR(str): def __init__(self, src): self.src = src def Rand(self, length=8, strs=None, mode='*'): if not isinstance(strs, str): if mode in ['all', '*', 'alphanumchar']: strs = '0aA-1b+2Bc=C3d_D,4.eE?5"fF6g7G!h8H@i9#Ij$JkK%lLmMn^N&oO*p(Pq)Q/r\Rs:St;TuUv{V<wW}x[Xy>Y]z|Z' elif mode in ['alphanum']: strs = 'aA1b2BcC3dD4eE5fF6g7Gh8Hi9IjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ' else: strs = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ' new = '' strn = len(strs) - 1 for i in range(0, length): new = '{0}{1}'.format(new, strs[random.randint(0, strn)]) return new def Cut(self, head_len=None, body_len=None, new_line='\n', out=str): if not isinstance(self.src, str): self.src = '''{}'''.format(self.src) source = self.src.split(new_line)
#Kage Park import ast import struct from klib.MODULE import * MODULE().Import('from klib.Type import Type') MODULE().Import('from klib.Misc import *') MODULE().Import('from klib.MAC import MAC') class CONVERT: def __init__(self, src): self.src = src def Int(self, default=False): if isinstance(self.src, int): return self.src print('>>', self.src, Type(self.src, 'str', 'float', 'long', 'str')) if Type(self.src, ('float', 'long', 'str')): try: return int(self.src) except: pass return default def Bytes(self, encode='utf-8'): if Py3: if isinstance(self.src, bytes): return self.src else: return bytes(self.src, encode) return bytes( self.src) # if change to decode then network packet broken
#Kage Park import socket import struct from distutils.spawn import find_executable from klib.MODULE import * MODULE().Import('from klib.Type import Type') MODULE().Import('from klib.Misc import *') MODULE().Import('from klib.TIME import TIME') MODULE().Import('from klib.SHELL import SHELL') def is_cancel(func): ttt=type(func).__name__ if ttt in ['function','instancemethod','method']: if func(): return True elif ttt in ['bool','str'] and func in [True,'cancel']: return True return False class IP: def __init__(self,src): self.src=src # if isinstance(src,str): # self.src=src.strip() # elif isinstance(src,int): # self.src=src # elif isinstance(src,hex): # self.src=src def IsV4(self,ip=None): if ip is not None:
def __init__(self): MODULE().Import('import postgresql')
#Kage park ####################################### # Load All files ####################################### import os from klib.MODULE import * for ii in os.listdir(os.path.dirname(__file__)): if ii in ['__init__.py', 'MODULE.py', 'test.py', 'setup.py']: continue ii_a = ii.split('.') if len(ii_a) == 2 and ii_a[-1] == 'py': MODULE().Import('klib.{} import *'.format(ii_a[0])) ####################################### # Load defined Files ####################################### # from klib.MODULE import * # from klib.Type import Type # from klib.Misc import * # from klib.IS import IS # from klib.DICT import DICT # from klib.LIST import LIST # from klib.GET import GET # from klib.CONVERT import CONVERT # from klib.BMC import * # from klib.PRINT import * # from klib.PING import * # from klib.IP import IP