函数的Python集合。

pcof的Python项目详细描述


pcof-Python函数集合

{1}$ PyPI - Python VersionPyPIcodecovGitHub LicenseCode style: black

pcof是一个小的有用函数的集合。在

安装

pip install pcof

大多数函数没有任何外部依赖关系。 如果脚本不使用任何具有依赖关系的pcof函数,则可以 安装pcof并忽略其依赖项。在

^{pr2}$

使用示例

>>>frompcofimportbytesconv>>>bytesconv.bytes2human(88191837473)('82.14','GB')>>>bytesconv.bytes2human(88191837473,unit='MB')('84106.29','MB')>>>bytesconv.bytes2human(88191837473,unit='MB',precision=0)('84106','MB')>>>bytesconv.human2bytes(100,'GB')'107374182400.00'>>>bytesconv.human2bytes(100,'GB',base=1000)'100000000000.00'>>>bytesconv.bandwidth_converter(100,from_unit="Mbps",to_unit="MB")(12.5,'MB/seconds')>>>bytesconv.bandwidth_converter(10,from_unit="Gbps",from_time="seconds",to_unit="GB",to_time="minutes")(75.0,'GB/minutes')>>>bytesconv.bandwidth_converter(6,from_unit="GB",from_time="hours",to_unit="Mbps",to_time="seconds")(13.333333333333334,'Mbps/seconds')>>>frompcofimportdatetimefunc>>>datetimefunc.epoch_time_now()1591041372>>>datetimefunc.epoch_time_min_ago(60)1591037781>>>datetimefunc.epoch_time_hours_ago(12)1590998197>>>datetimefunc.epoch_time_days_ago(30)1588449403>>>datetimefunc.epoch_time_to_human(1590175926)'Fri May 22 16:32:06 2020'>>>datetimefunc.epoch_time_to_human(1590175926,utc='yes',date_format='%m/%d/%Y %H:%M:%S')'05/22/2020 19:32:06'>>>datetimefunc.seconds_to_human(300)'5 Minutes'>>>datetimefunc.seconds_to_human(310)'5 Minutes, 10 Seconds'>>>datetimefunc.seconds_to_human(8481083)'3 Months, 8 Days, 3 Hours, 51 Minutes, 23 Seconds'>>>datetimefunc.time_unit_conversion(90,from_unit="days",to_unit="months")'3'>>>frompcof.pctimportx_pct_of_number>>>x_pct_of_number(40,200)# 40% of 200'80.00'>>>frompcofimportprinttable>>>header=["col1","col2"]>>>rows=[["line1_col1","line1_col2"],["line2_col1","line2_col2"]]>>>pcof.print_table(header,rows)+------------+------------+|col1|col2|+------------+------------+|line1_col1|line1_col2||line2_col1|line2_col2|+------------+------------+>>>frompcofimportmisc>>>misc.checksum_file("tests/file_checksum.txt")'f133e784590eae8c07dac9295ae50344731090dbfc848c1d77d0af4a79a56f21'>>>misc.checksum_file("tests/file_checksum.txt",algorithm='md5')'f978067032b567b197cef53a4d463a89'>>>importtime>>>frompcofimportdecorators>>>@decorators.time_elapsed(print_info=True)...defmyfunc():...time.sleep(1)...>>>myfunc()Decoratortime_elapsed:myfuncargs:()kwargs:{}-elapsedtime1.0012seconds.Thisfunctionallexecutionelapsedtime:1.0012seconds>>>myfunc()Decoratortime_elapsed:myfuncargs:()kwargs:{}-elapsedtime1.0011seconds.Thisfunctionallexecutionelapsedtime:2.0023seconds>>>frompcof.downloadfileimportdownload_file>>>download_file("http://google.com/favicon.ico","/tmp/google.ico")

可用功能列表

功能

ModuleNameDescriptionDependencies
miscmsgPrint colored text.-
miscsend_emailSend an email using smtplib module.-
miscsetup_loggingConfigure logging.-
miscnested_dictReturn a nested dictionary (arbitrary number of levels).-
miscfind_keyReturn a value for a key in a dictionary.-
miscreturn_dict_valueReturn a value from a dictionary.-
miscrun_cmdExecute a command on the operating system.-
miscchecksum_fileReturn checksums (hash) of a file.-
bytesconvbytes2humanConvert number in bytes to human format.-
bytesconvhuman2bytesConvert size from human to bytes.-
bytesconvbandwidth_converterBandwidth Calculator.-
datetimefuncepoch_time_to_humanConvert a unix epoch time to human format.-
datetimefuncepoch_time_nowReturn current date and time in unix epoch time format.-
datetimefuncepoch_time_min_agoReturn current date and time less x minutes in unix epoch time format.-
datetimefuncepoch_time_hours_agoReturn current date and time with less x hours in unix epoch time format.-
datetimefuncepoch_time_days_agoReturn current date and time with less x days in unix epoch time format.-
datetimefunctime_unit_conversionConvert number from a time unit to another time unit.-
datetimefuncseconds_to_humanConvert number in seconds to human format.-
pcty_what_pct_of_xCalculate the percentage of number1 to number2.-
pctx_pct_of_numberCalculate what is the x% of a number.-
pctpct_change_from_x_to_yCalculate percent increase/decrease from number1 to number2.-
printtableprint_tablePrint table using module prettytable.prettytable
pytzconvert_datetime_to_tzConvert a date to a specific timezone.pytz
downloadfiledownload_fileDownload a file.requests

装饰师

^{tb2}$

文档(使用pydoc自动生成)

Help on module misc:

NAME
    misc - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Miscellaneous functions

FUNCTIONS
checksum_file(filename,*,algorithm='sha256',block_size=1048576)Returnchecksums(hash)ofafile.Arguments:filename(str):filetocheckhashKeywordarguments(opt):algorithm(str):algorithmusedtocalculatehash.default:sha256block_size(int):chunksizetoreadthefile(bytes)return:hex-encodedstringExample:>>>checksum_file("my_file")# doctest: +SKIP'179b8c9510b2f068b94286c86610c6fe633ca44b5e541837ae9461bbdace7191'>>>checksum_file("my_file",algorithm="md5")# doctest: +SKIP'bdc28791ea81bafa7601e98f68b692e5'find_key(dict_obj,key)Returnavalueforakeyinadictionary.FunctiontoloopoveradictionaryandsearchforanspecifickeyItsupportsnesteddictionaryArguments:dict_obj(obj):Alistoradictionarykey(str):dictionarykeyReturn:(list):alistwithvaluesthatmatchesthekeyExample:>>>x={"A1":"A","B1":{"A2":"AA"}}>>>find_key(x,"A1")['A']>>>find_key(x,"A2")['AA']>>>find_key(x,"YY")[]>>>x={"A1":"A","B1":{"A1":"AA"}}>>>find_key(x,"A1")['A','AA']msg(color,msg_text,exitcode=0,*,end='\n',flush=True,output=None)Printcoloredtext.Arguments:color(str):colorname(blue,red,green,yellow,cyanornocolor)msg_text(str):texttobeprintedexitcode(int,opt):Optionalparameter.Ifexitcodeisdifferentfromzero,itterminatesthescript,i.e,itcallssys.exitwiththeexitcodeinformedKeywordarguments(optional):end(str):stringappendedafterthelastcharin"msg_text"defaultanewlineflush(True/False):whethertoforciblyflushthestream.defaultTrueoutput(stream):afile-likeobject(stream).defaultsys.stdoutExample:msg("blue","nice text in blue")msg("red","Error in my script. terminating",1)nested_dict()Returnanesteddictionary(arbitrarynumberoflevels).Example:>>>mydict=nested_dict()>>>mydict['a1']['b1']['c1']='test_1'>>>mydict['a1']['b2']='test_2'>>>mydict['a1']['b3']='test_3'>>>mydict.keys()dict_keys(['a1'])>>>mydict['a1'].keys()dict_keys(['b1','b2','b3'])>>>mydict['a1']['b1'].keys()dict_keys(['c1'])>>>mydict['a1']['b1']['c1']'test_1'>>>mydict['a1']['b2']'test_2'>>>print(mydict)# doctest: +SKIPdefaultdict(<functionnested_dictat0x7f0239f4aee0>,{'a1':defaultdict(<functionnested_dictat0x7f0239f4aee0>,{'b1':defaultdict(<functionnested_dictat0x7f0239f4aee0>,{'c1':'test_1'}),'b2':'test_2','b3':'test_3'})})return_dict_value(dictionary,keys,*,ignore_key_error=False)Returnavaluefromadictionary.Recursivelyiterateoveradictionaryandreturnvalueforthekey.Keymustbealist.EachelementofthelistreferstothelevelofthedicionaryIthelpstoreducenumberofcodelineswhenweneedtoperformmaytry:except:tocatchKeyErrorsArguments:dictionary(dict):Dictionarykeys(list):Listwithkey(s)ignore_key_error(True/False):Ignorekeynotfounderrors:True-return''ifkeynotfoundFalse-raiseexceptiondefault:FalseExample:>>>mydic={'a':'value_a',...'b':{...'b1':'value_b1',...'b2':'value_b2'...},...'c':{...'c1':{...'c11':'value_c11',...'c12':'value_c12'...}...},...}>>>return_dict_value(mydic,['a'])'value_a'>>>return_dict_value(mydic,['b']){'b1':'value_b1','b2':'value_b2'}>>>return_dict_value(mydic,['b','b1'])'value_b1'>>>return_dict_value(mydic,['c','c1','c12'])'value_c12'>>>return_dict_value(mydic,['c','c1','c13'])Traceback(mostrecentcalllast):...KeyError:'c13'>>>return_dict_value(mydic,['c','c1','c13'],ignore_key_error=True)''>>>return_dict_value(mydic,['x'],ignore_key_error=True)''run_cmd(cmd)Executeacommandontheoperatingsystem.Arguments:cmd(str):thecommandtobeexecutedReturn:-Ifcommandcompletewithreturncodezeroreturn:command_return_code,stdout-Ifcommandcompleteswithreturncodedifferentfromzeroreturn:command_return_code,stderrExample:>>>run_cmd("echo test")(0,'test\n')>>>run_cmd("cmd_does_not_exist")# doctest:+ELLIPSIS(127,'...cmd_does_not_exist:...not found\n')send_email(mail_from,mail_to,subject,body,mailserver='localhost')Sendanemailusingsmtplibmodule.Arguments:mail_from(str):sendemailfromthisaddressmail_to(str):sendemailtothisaddresssubject(str):mailsubjectmail_server(str,opt):mailserveraddress.Defaultislocalhostsetup_logging(logfile=None,*,filemode='a',date_format=None,log_level='DEBUG')Configurelogging.Arguments(opt):logfile(str):logfiletowritethelogmessagesIfnotspecified,itshowslogmessagesonscreen(stderr)Keywordarguments(opt):filemode(a/w):a-logmessagesareappendedtothefile(default)w-logmessagesoverwritethefiledate_format(str):dateformatinstrftimeformatdefaultis%m/%d/%Y%H:%M:%Slog_level(str):specifiesthelowest-severitylogmessageDEBUG,INFO,WARNING,ERRORorCRITICALdefaultisDEBUG
Help on module bytesconv:

NAME
    bytesconv - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Bytes calculator

FUNCTIONS
bandwidth_converter(number,*,from_unit,to_unit,from_time='seconds',to_time='seconds')BandwidthCalculator.Convertdataratefromoneunittoanother.Arguments:number(int):numbertobeconvertedKeywordarguments:from_unit(str):convertfromthisdataunit.Example:(bps,Kbps,Mbps,Gbps...KB,KiB,MB,MiB...)to_unit(str):converttothisdataunit.Example:(bps,Kbps,Mbps,Gbps...KB,KiB,MB,MiB...)Keywordarguments(opt):from_time(str):Specifythetimeframeusedinfrom_unit(seconds,minutes,hours,days,months)default:secondsto_time(str):Specifythetimeframeusedinto_unit(seconds,minutes,hours,days,months)default:secondsbps,Kbps,Mbps,Gbps...=decimalbase=1000^nKB,MB,GB,TB...=decimalbase=1000^nKiB,MiB,GiB,TiB...=binarybase=1024^nReferences:-https://en.wikipedia.org/wiki/Units_of_information-https://physics.nist.gov/cuu/Units/binary.htmlReturns:tuple(number_converted,to_unit/to_time)Example:>>>bandwidth_converter(100,from_unit="Mbps",to_unit="MB")(12.5,'MB/seconds')>>>bandwidth_converter(100,from_unit="Mbps",to_unit="GB",to_time="hours")(45.0,'GB/hours')>>>bandwidth_converter(1,from_unit="Gbps",to_unit="MB")(125.0,'MB/seconds')>>>bandwidth_converter(10,from_unit="Gbps",to_unit="GB")(1.25,'GB/seconds')>>>bandwidth_converter(10,from_unit="Gbps",to_unit="TB",to_time="hours")(4.5,'TB/hours')>>>bandwidth_converter(10,from_unit="GB",to_unit="Gbps")(80.0,'Gbps/seconds')>>>Convert2.25GBperhourstoMbps# doctest: +SKIP>>>bandwidth_converter(2.25,from_unit="GB",from_time="hours",to_unit="Mbps",to_time="seconds")# noqa(5.0,'Mbps/seconds')bytes2human(size,*,unit='',precision=2,base=1024)Convertnumberinbytestohumanformat.Arguments:size(int):bytestobeconvertedKeywordarguments(opt):unit(str):Ifitwillconvertbytestoaspecificunit'KB','MB','GB','TB','PB','EB'precision(int):numberofdigitsafterthedecimalpointbase(int):1000-fordecimalbase1024-forbinarybase(itisthedefault)Returns:(int):number(str):unit('Bytes','KB','MB','GB','TB','PB','EB','ZB']Example:>>>bytes2human(10)('10.00','Bytes')>>>bytes2human(2048)('2.00','KB')>>>bytes2human(27273042329)('25.40','GB')>>>bytes2human(27273042329,precision=1)('25.4','GB')>>>bytes2human(27273042329,unit='MB')('26009.60','MB')human2bytes(size,unit,*,precision=2,base=1024)Convertsizefromhumantobytes.Arguments:size(int):numberunit(str):convertsfromthisunittobytes'KB','MB','GB','TB','PB','EB'Keywordarguments(opt):precision(int):numberofdigitsafterthedecimalpointdefaultis2base(int):1000-fordecimalbase1024-forbinarybase(itisthedefault)Returns:(int)numberinbytesExample:>>>human2bytes(10,'GB')'10737418240.00'>>>human2bytes(10,'GB',precision=0)'10737418240'>>>human2bytes(10,'PB')'11258999068426240.00'
Help on module datetimefunc:

NAME
    datetimefunc - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Date and time functions

FUNCTIONS
epoch_time_days_ago(days=1,*,utc='no')Returncurrentdateandtimewithlessxdaysinunixepochtimeformat.Unixepochtime-numberofsecondsthathaveelapsedsince00:00:00CoordinatedUniversalTime(UTC),1January1970Arguments(opt):days(int):Numberofdaysagotoreturnunixtimestampdefaultis1dayKeywordarguments(opt):utc(yes/no):IfunixepochtimeinUTCtimezonedefaultisnoExample:>>>epoch_time_days_ago()# doctest: +SKIP1530239517>>>epoch_time_days_ago(7)# doctest: +SKIP1529721118epoch_time_hours_ago(hours=1,*,utc='no')Returncurrentdateandtimewithlessxhoursinunixepochtimeformat.Unixepochtime-numberofsecondsthathaveelapsedsince00:00:00CoordinatedUniversalTime(UTC),1January1970Arguments(opt):hours(int):Numberofhoursagotoreturnunixtimestampdefaultis1hourKeywordarguments(opt):utc(yes/no):IfunixepochtimeinUTCtimezonedefaultisnoExample:>>>epoch_time_hours_ago()# doctest: +SKIP1530322279>>>epoch_time_hours_ago(8)# doctest: +SKIP1530297083epoch_time_min_ago(minutes=5,*,utc='no')Returncurrentdateandtimelessxminutesinunixepochtimeformat.Unixepochtime-numberofsecondsthathaveelapsedsince00:00:00CoordinatedUniversalTime(UTC),1January1970Arguments(opt):minutes(int):Numberofminutesagotoreturnunixtimestampdefaultis5minutesKeywordarguments(opt):utc(yes/no):IfunixepochtimeinUTCtimezonedefaultisnoExample:>>>epoch_time_min_ago()# doctest: +SKIP1530325377>>>epoch_time_min_ago(30)# doctest: +SKIP1530323879epoch_time_now(*,utc='no')Returncurrentdateandtimeinunixepochtimeformat.Unixepochtime-numberofsecondsthathaveelapsedsince00:00:00CoordinatedUniversalTime(UTC),1January1970Arguments:utc(yes/no):IfreturnsunixepochtimeinUTCtimezonedefaultisnoExample:>>>epoch_time_now()# doctest: +SKIP1530325275epoch_time_to_human(epoch,*,date_format='%c',utc='no')Convertaunixepochtimetohumanformat.Unixepochtime-numberofsecondsthathaveelapsedsince00:00:00CoordinatedUniversalTime(UTC),1January1970Arguments:epoch(int):unixepochtime(timestamp)Keywordarguments(opt):date_format(str):strftimeformattoshowtheepochtimedefaultis'%c'(Localesappropriatedateandtimerepresentation)utc(yes/no):IfunixepochtimeinUTCtimezonedefaultisnoExample:>>>epoch_time_to_human(1530324373,date_format='%m%d%Y %H:%M:%S',utc='yes')'06302018 02:06:13'>>>epoch_time_to_human(1530324373)# doctest: +SKIP'Fri Jun 29 23:06:13 2018'>>>epoch_time_to_human(1530324373,utc='yes')# doctest: +SKIP'Sat Jun 30 02:06:13 2018'seconds_to_human(seconds,*,unit=None)Convertnumberinsecondstohumanformat.Arguments:seconds(int):NumberofsecondsKeywordarguments(opt):unit(Months/Days/Hours/Minutes/Seconds):MaxunitusedtoconvertExample:>>>seconds_to_human(300)'5 Minutes'>>>seconds_to_human(310)'5 Minutes, 10 Seconds'>>>seconds_to_human(10810)'3 Hours, 10 Seconds'>>>seconds_to_human(10810,unit='Minutes')'180 Minutes, 10 Seconds'>>>seconds_to_human(180072)'2 Days, 2 Hours, 1 Minutes, 12 Seconds'>>>seconds_to_human(5191272)'2 Months, 2 Hours, 1 Minutes, 12 Seconds'time_unit_conversion(number,*,from_unit,to_unit,precision=0,days_month=30,days_year=365)Convertnumberfromatimeunittoanothertimeunit.Arguments:number(int):numbertoconvertKeywordarguments:from_unit(seconds/minutes/hours/days/weeks/months/years):unittoconvertfromto_unit(seconds/minutes/hours/days/weeks/months/years):unittoconverttoKeywordarguments(opt):precision(int):numberofdigitsafterthedecimalpoint(default0)days_month(int/float):numberofdaysineachmonth(default30)days_year(int/float):numberofdaysineachyear(default365)Return:numberconvertedtonewunitExample:>>>time_unit_conversion(3600,from_unit="seconds",to_unit="hours")'1'>>>time_unit_conversion(1400,from_unit="minutes",to_unit="days")'1'>>>time_unit_conversion(36,from_unit="hours",to_unit="days",precision=1)'1.5'>>>time_unit_conversion(90,from_unit="days",to_unit="months")'3'
Help on module pct:

NAME
    pct - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Percentage Calculator

FUNCTIONS
pct_change_from_x_to_y(number1,number2,*,precision='2')Calculatepercentincrease/decreasefromnumber1tonumber2.Arguments:number1(int):startvalue(from)number2(int):endvalue(to)Keywordarguments(opt):precision(int):numberofdigitsafterthedecimalpointdefaultis2Returns:(str):numberExample:>>>pct_change_from_x_to_y(100,110)# what is the pct increase from 100 to 110?'10.00%'>>>pct_change_from_x_to_y(100,90)# what is the pct from 100 to 90?'-10.00%'>>>pct_change_from_x_to_y(25,50,precision=0)'100%'x_pct_of_number(pct,number,*,precision='2')Calculatewhatisthex%ofanumber.Arguments:pct(int):percentagenumber(int):numberKeywordarguments(opt):precision(int):numberofdigitsafterthedecimalpointdefaultis2Returns:(str):numberExample:>>>x_pct_of_number(33.333,90)# what is 33.333% of 90?'30.00'>>>x_pct_of_number(40,200)# what is 40% of 200?'80.00'>>>x_pct_of_number(40.9,200)# what is 40.9% of 200?'81.80'>>>x_pct_of_number(40.9,200,precision=4)'81.8000'>>>x_pct_of_number(40.9,200,precision=0)'82'y_what_pct_of_x(number1,number2,*,precision='2')Calculatethepercentageofnumber1tonumber2.Number1iswhatpercentofnumber2.Arguments:number1(int):numbernumber2(int):numberKeywordarguments(opt):precision(int):numberofdigitsafterthedecimalpointdefaultis2Returns:(str):PctvalueExample:>>>y_what_pct_of_x(30,90)# 30 is what percent of 90?'33.33%'>>>y_what_pct_of_x(30,90,precision=0)'33%'>>>y_what_pct_of_x(30,90,precision=4)'33.3333%'>>>y_what_pct_of_x(10,50,precision=0)# 10 is what percent of 50?'20%'
Help on module printtable:

NAME
    printtable - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Dependencies: prettytable

FUNCTIONS
print_table(header,rows,*,sortby='',alignl='',alignr='',hrules='')Printtableusingmoduleprettytable.Arguments:header(list):Listwithtableheaderrows(list):Nestedlistwithtablerows[[row1],[row2],[row3],...]Keywordarguments(optional):sortby(str):headernametosorttheoutputalignl(list):headersnametoaligntoleftalignr(list):headersnametoaligntorighthrules(str):Controlsprintingofhorizontalrulesafterrows.Allowedvalues:FRAME,HEADER,ALL,NONEExample:>>>header=["col1","col2"]>>>rows=[["line1_col1","line1_col2"],["line2_col1","line2_col2"]]>>>print_table(header,rows)+------------+------------+|col1|col2|+------------+------------+|line1_col1|line1_col2||line2_col1|line2_col2|+------------+------------+
Help on module pytz:

NAME
    pytz - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Dependencies: pytz

FUNCTIONS
convert_datetime_to_tz(*,date,date_fmt,from_tz='UTC',to_tz='America/Sao_Paulo')Convertadatetoaspecifictimezone.Keywordarguments:date(str):datetoconvertdate_fmt(str):formatofthedatetoconvertfrom_tz(timezone):sourcetimezonename(default:UTC)to_tz(timezone):targettimezonename(default:America/Sao_Paulo)Returns:datetimeobjectwiththetargettimezonedefined.Example:# convert a date from utc to America/Sao_Paulo>>>convert_datetime_to_tz(date='2019-04-26T10:38:05Z',# doctest: +SKIPdate_fmt="%Y-%m-%dT%H:%M:%SZ")datetime.datetime(2019,4,26,7,38,5,tzinfo=<DstTzInfo'America/Sao_Paulo'-03-1day,21:00:00STD>)# convert date from America/Sao_Paulo to America/Los_Angeles>>>convert_datetime_to_tz(date='2019-04-26T10:38:05Z',# doctest: +SKIPdate_fmt="%Y-%m-%dT%H:%M:%SZ",from_tz="America/Sao_Paulo",to_tz="America/Los_Angeles")datetime.datetime(2019,4,26,6,38,5,# doctest: +SKIPtzinfo=<DstTzInfo'America/Los_Angeles'PDT-1day,17:00:00DST>)# Convert date from America/New_York to Asia/Dubai>>>convert_datetime_to_tz(date='2019-04-26T10:38:05Z',# doctest: +SKIPdate_fmt="%Y-%m-%dT%H:%M:%SZ",from_tz="America/New_York",to_tz="Asia/Dubai")datetime.datetime(2019,4,26,18,38,5,tzinfo=<DstTzInfo'Asia/Dubai'+04+4:00:00STD>)
Help on module downloadfile:

NAME
    downloadfile - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Dependencies: requests

FUNCTIONS
download_file(url,local_file,*,allow_redirects=True,decode=True)Downloadafile.Arguments:url(str):URLtodownloadlocal_file(str):LocalfilenametostorethedownloadedfileKeywordarguments(opt):allow_redirects(True/False):Allowrequesttoredirecturldefault:Truedecode(True/False):Decodecompressedresponseslikegzipdefault:TrueReturn:RequestresponseheadersExample:>>>download_file("http://google.com/favicon.ico",# doctest: +SKIP"/tmp/google.ico")
Help on module decorators:

NAME
    decorators - Python Collection Of Functions.

DESCRIPTION
    Package with collection of small useful functions.

    Decorators functions

FUNCTIONS
debug(_func=None,*,loglevel='DEBUG',print_info=False)Showfunctionparametersandreturnvalues.Decoratorkeywordarguments(optional):loglevel(str):loglevelusedtoshowdebuginformation.(defaultDEBUG)print_info(True/False):printdebuginformation.(defaultFalse)Example:@debugdefmy_func():print("my func")returnTrue@debug(print_info=True)defmy_other_func(my_param):print("my other func")num_calls(_func=None,*,loglevel='DEBUG',print_info=False)Countthenumberoftimesafunctioniscalled.Decoratorkeywordarguments(optional):loglevel(str):loglevelusedtoshowthenumberofcallsinformation.(defaultDEBUG)print_info(True/False):printfunctionnumberofcallinformation(defaultFalse)Example:@num_callsdefmy_func():print("my func")@num_calls(print_info=True)defmy_other_func():print("my other func")retry_on_exception(_func=None,*,exception=(<class'Exception'>,), loglevel='DEBUG', max_retry=5, sleep_retry=1, exception_error=None)Retryfunctionexecutionifexceptionraises.Decoratorkeywordarguments(optional):exception(tuple):Tuplewithexceptionsthatdecoratorwillretryfunction's execution(defaultanyexception)loglevel(str):Loglevelusedtoshowdebuginformation.(defaultDEBUG)max_retry(int):Maxnumberofretries.-1toretryforever(default5)sleep_retry(int):Timeinsecondstowaitbetweenretries(default1)exception_error(exception):Exceptionthatdecoratorwillraiseifmax_retryisreachedwithoutsuccess(defaultthesameexceptionfunctionraises)Example:# Retry function if any exception raise@retry_on_exceptiondefmy_func():print("my func")raise(TimeoutError)# Retry only with exceptions: TimeoutErrorr, IndexError and Retry max of 10 times@retry_on_exception(exception=(TimeoutError,IndexError),max_retry=10)defmy_other_func(my_param):print("my other func")time_elapsed(_func=None,*,loglevel='DEBUG',print_info=False)Calculateelapsedtimeinseconds.Decoratorkeywordarguments(optional):loglevel(str):loglevelusedtoshowelapsedtime(defaultDEBUG)print_info(True/False):printelapsedtime(defaultFalse)Example:@time_elapseddefmy_func():print("my func")@time_elapsed(print_info=True)defmy_other_func():print("my other func")

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java为什么只为字符数组重载println方法,而不为字符串、整数等其他数组重载?   java将快速线程返回到池中,而不是等待慢速线程   创建jar文件时java SwingWorker不工作   java如何将依赖注入RabbitListener   java如何在gradle任务中通过scp复制目录?   java在MySql数据库中创建表时,遇到NullPointerException   java HTTP Status 500 Servlet执行引发异常   在JAVA中对arraylist使用继承时出错   java PowerMockito未完成存根异常   如果没有错误/警告增加到某个极限,java是否停止在eclipse中构建项目或使用maven?   java Robolectric如何测试DateFormat。getBestDateTimePattern()   google云平台GCP数据存储Java API,构建一个空值实体   VerifyListener和FocusListener之间的java冲突   安卓是否可以在Java中的另一个方法内部强制调用一个方法?   JavaWindows7、JDK1.8、SpringBoot应用程序JAR在方法安全性方面占用了大量时间。getProviders()返回   Bean提供程序的java错误消息   java Slick动画每帧必须有一个持续时间   java无法在Trie中设置isLeaf标志   java为什么JVM不能创建包含main方法的类的对象,以便从该类访问main方法,如果它具有该类的名称?   java Apache Camel+CXF端点身份验证