Package: wrenchbox
Wrenchbox for PythonA set of utilities for daily development.本项目是一些常用的 Python 工具集合。Installpipinstall-UwrenchboxUsageAlert HanlderSend alerts to certain bots or web APIs.通过钉钉机器人等渠道发送报警信息。$python3-u-mwrenchbox.alert-h
usage:alert.py[-h][--debug]--typeTYPE[--tokenTOKEN]msg

positionalarguments:msgthemessage

optionalarguments:-h,--helpshowthishelpmessageandexit--debugshowdebuginformation--typeTYPE,-pTYPEalerttype,mustbe"dingtalk"--tokenTOKEN,-kTOKENaccesstoken,ifanyfromwrenchbox.alertimportDingTalkDingTalk('token').send('This is a warning message.')200Configuration ParserRead a configuration from a YAML or JSON file.从 YAML 或 JSON 中读取一段配置信息。$python3-u-mwrenchbox.config-h
usage:config.py[-h][--debug]config

positionalarguments:configconfigfile

optionalarguments:-h,--helpshowthishelpmessageandexit--debugshowdebuginformationfromwrenchbox.configimportConfigurationprint(json.dumps(Configuration('wrenchbox/config.yml').__dict__,indent=2)){"version":0,"name":"00000000-0000-0000-0000-000000000000","config":{"key":"value","nested":{"key":"value"},"list":[{"key":"value"},{"key":"value"}]}}The following configurations will be automatically generated if not provided:versionversion of the configuration file, could be verified throughConfiguration(version=(0,))workerID of the worker, default: 0namename of the worker, anUUIDwill be generated if not providedAll configuration keys starting with-or.will be ignored (these keys should be used as audition only).Database HanlderAn advanced database handler based onSQLAlchemy.一个基于SQLAlchemy开发的更简单的数据库处理模块。fromwrenchbox.databaseimportDatabaseHandlerDatabaseHandler({'test':'sqlite:///test.db'},[('test','test')]).handle('test',{'id':1},{'id':1,'name':str(datetime.now())},replace=True)The above code will insert or update a record withid=1.Datetime HanlderAn advanced datetime handler based onpython-dateutil.一个基于python-dateutil开发的更简单的日期和时间处理器。fromwrenchbox.datetimeimportTprint(T().timestamp())# Get timestampprint(T().format())# Format into YYYY-MM-DD HH:MM:SSprint(T().format('d'))# Format into YYYY-MM-DDprint(T().format('t'))# Format into HH:MM:SS1598930603.003622
2020-09-01 11:23:23
2020-09-01
11:23:23When initialisingT, it is possible to pass the following arguments:Nonecurrent timestamp will be generateddatetime.datetimewill be directly usedfloatorintwill be parsed as timestampstrwill be parsed throughpython-dateutilDictionary HanlderAn advanced dictionary hander providing various tools.提供了多种多样的字典（dict）处理工具。fromwrenchbox.dictimportEnhancedDictdict_a={'a':'a','b':{'a':1,'b':{'a':1,'b':[{'a':1,'b':2},{'a':1,'b':{'a':1,'b':2}}]}}}dict_b={'a':1,'b':{'b':{'b':2}}}print(dict_a)print(dict_b)print(EnhancedDict(dict_a).search('a'))print(EnhancedDict(dict_a).merge(dict_b))print(EnhancedDict(dict_b).flatten())print(EnhancedDict(dict_a).format(lambdax:x+10,lambdax:isinstance(x,int)))print(EnhancedDict(dict_a).remove_key('a'))print(EnhancedDict(dict_a).remove_value(1)){"a":"a","b":{"a":1,"b":{"a":1,"b":[{"a":1,"b":2},{"a":1,"b":{"a":1,"b":2}}]}}}{"a":1,"b":{"b":{"b":2}}}["a",1,1,1,1,1]{"a":1,"b":{"a":1,"b":{"a":1,"b":2}}}{"a":1,"b_b_b":2}{"a":"a","b":{"a":11,"b":{"a":11,"b":[{"a":11,"b":12},{"a":11,"b":{"a":11,"b":12}}]}}}{"b":{"b":{"b":[{"b":2},{"b":{"b":2}}]}}}{"a":"a","b":{"b":{"b":[{"b":2},{"b":{"b":2}}]}}}IO HandlerAn advanced IO handerl providing various tools.提供了多种多样的 IO 工具。fromwrenchbox.ioimportBufferedWriterw=BufferedWriter(buffer=50)foriinrange(100):w.write(i)w.close()The above code will write two separate files with 50 records each.List HanlderAn advanced list hander providing various tools.提供了多种多样的列表（list）处理工具。fromwrenchbox.listimportEnhancedListlist_a=[1,[1,[2,3],2],2]print(list_a)print(EnhancedList(list_a).flatten())# Flatten the list and put all sub-lists into the root levelprint(EnhancedList(list_a).pick(lambdax:x==1))# Pick values based on a functionprint(EnhancedList(list_a).format(lambdax:x+1,lambdax:isinstance(x,(int,float))))# Format values of the list through a filter[1,[1,[2,3],2],2][1,1,2,3,2,2][1,[1]][[[2,3],2],2][2,[2,[3,4],3],3]Logging ToolsA series of tools for logging.提供了美化的日志工具。fromwrenchbox.loggingimportsetup_log,progress# Create a colorized logger and print logging messagessetup_log(level=logging.DEBUG,path='./log/',tag='wrenchbox')logging.debug('This is a DEBUG message.')logging.info('This is an INFO message.')logging.warning('This is a WARNING message.')logging.error('This is an ERROR message.')logging.critical('This is an CRITICAL message.')# Show a progress barfor_iinrange(100):progress(_i,100)time.sleep(0.02)[2020-09-28 10:18:40,084] This is a DEBUG message.
[2020-09-28 10:18:40,084] This is an INFO message.
[2020-09-28 10:18:40,084] This is a WARNING message.
[2020-09-28 10:18:40,085] This is an ERROR message.
[2020-09-28 10:18:40,085] This is an CRITICAL message.
[==========================================================--] 97.0%Logs are colorized with the following default config:{DEBUG:"cyan",INFO:"green",WARNING:"yellow",ERROR:"red",CRITICAL:"magenta"}Number HanlderAn advanced number hander providing various tools.提供了多种多样的数字（number）处理工具。fromwrenchbox.numberimportEnhancedDecimalprint(EnhancedDecimal('3.1415926').round(Decimal('0.1')))# Round a decimal with any unit like in excel3.1Object ToolsA series of objects for specific uses.提供了一些杂项对象。Dict2StrSafe: a class that correctly convertsself.__dict__to a JSON string without errorsMunch: an alternative implementation ofMunchSnowflake Code GeneratorGenerate a series ofTwitter Snowflake Codes.生成若干Twitter Snowflake Codes。$python3-u-mwrenchbox.snowflake-h
usage:snowflake.py[-h][--debug][--twepochTWEPOCH][-dD]-wWn

positionalarguments:n# of resultsoptionalarguments:-h,--helpshowthishelpmessageandexit--debugshowdebuginformation--twepochTWEPOCHtwitterepoch,default:1483228800000-dDdatacenterid,default:31-wWworkerid,0-31fromwrenchbox.snowflakeimportSnowflakeprint(next(Snowflake(twepoch=1483228800000).generate(31)))495059711868006400String HandlerAn advanced string hander providing various tools.提供了多种多样的字符串（string）处理工具。fromwrenchbox.stringimportdigits,random_chars,random_letters,random_numbersprint(digits(pi))# Count the digits of a given float numberprint(random_chars(3))# Generate a random string from [a-zA-Z0-9]print(random_letters(3))# Generate a random string from [a-zA-Z]print(random_numbers(3))# Generate a random string from [0-9]15
63f
FVK
007Text HandlerA set of advanced text processing modules.提供了多种多样的文本处理工具。$python3-u-mwrenchbox.text-h
usage:text.py[-h][--debug][--chinese][-pP]f

positionalarguments:ffilepath

optionalarguments:-h,--helpshowthishelpmessageandexit--debugshowdebuginformation--chinesespecifytheinputasChinese-pPpartofspeechtoshow,onlyworksforChinesefromwrenchbox.textimportSprint([iforiinS(open('test.txt','r').read()).v(chinese=True).wordsifi[1]in('v',)])[("是","v",8),("获取","v",1)]