Python单行命令

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

Python单行命令PowerfulPythonOne-LinersThisisapagethatisdevotedtoshortprogramsthatcanperformpowerfuloperations.Theabilitytowriteshortprogramsthatarejustaspowerfulasaprogramwritteninanotherlanguagedesignedtodothesamething.However,itissometimesfuntotryandwriteaprograminPythonthatisonlyoneline.Inotherlanguagesthiswouldbenearlyimpossible,butinPythonitisaloteasiertodo.Thetrickistothinkupsomethingthatwilldoalotwithalittle.I,personally,wouldlovetoseethispageexpandedtothepointwhereitneedssomesortoforganizationsystem.ThanksforYourCode,JAMOfcourse,thereisdebateonwhetherone-linersareevenPythonic.ContributedCodeJAM/Code/PlatformFinder-Thisprogramtellsyouwhatplatformyouareusing.JAM/Code/ComPYiler-Thisprogramcompilesevery.pyfileinthePythondirectory.PowerfulPythonOne-Liners/Hostname-Thisprogramstellsyouwhatyourhostnameis.Somethoughtsbyewo:Wanttoknowmanybytesaterabyteis?Ifyouknowfurtherabbreviations,youcanextendthelist.importpprint;pprint.pprint(zip(('Byte','KByte','MByte','GByte','TByte'),(110*iforiinxrange(5))))Andwhat'sthelargestnumberthatcanberepresentedby8Byte?print'\n'.join(%iByte=%iBit=largestnumber:%i%(j,j*8,256**j-1)forjin(1iforiinxrange(8)))Cute,isn'tit?SetofallsubsetsFunctionthatreturnsthesetofallsubsetsofitsargumentf=lambdax:[[yforj,yinenumerate(set(x))if(ij)&1]foriinrange(2**len(set(x)))]f([10,9,1,10,9,1,1,1,10,9,7])[[],[9],[10],[9,10],[7],[9,7],[10,7],[9,10,7],[1],[9,1],[10,1],[9,10,1],[7,1],[9,7,1],[10,7,1],[9,10,7,1]]-RJWAlternately(shorter,morefunctionalversion):f=lambdal:reduce(lambdaz,x:z+[y+[x]foryinz],l,[[]])Decodeabase64encodedfileimportbase64,sys;base64.decode(open(sys.argv[1],rb),open(sys.argv[2],wb))EditingalistoffilesinplaceIcameupwiththisone-linerinresponsetoanarticlethatsaiditcouldn'tbedoneasanone-linerinPython.Whatthisdoesisreplacethesubstringatbyoponalllinesofallfiles(inplace)underthepathspecified(here,thecurrentpath).Caution:Don'trunthisonyourhomedirectoryoryou'regoingtogetallyourtextfilesedited.Togglelinenumbers1importsys,os,re,fileinput;a=[i[2]foriinos.walk('.')ifi[2]][0];[sys.stdout.write(re.sub('at','op',j))forjinfileinput.input(a,inplace=1)]Cleareris:importos.path;a=[fforfinos.listdir('.')ifnotos.path.isdir(f)]ReimplementingcutPrinteverylinefromaninputfilebutremovethefirsttwofields.python-cimportsys;[sys.stdout.write(''.join(line.split('')[2:]))forlineinsys.stdin]input.txtCrammingPythonintoMakefilesArelatedissueisembeddingPythonintoaMakefile.IhadareallylongscriptthatIwastryingtocramintoamakefilesoIautomatedtheprocess:importsys,redefmain():fh=open(sys.argv[1],'r')lines=fh.readlines()print'\tpython2.2-c`printf\\if1:\\n\\'forlineinlines:line=re.sub('[\\\'\()]','\\\g0',line)#grableadingwhitespace(shouldbemultiplesof4)andmakestheminto#tabswh_spc_len=len(re.match('\s*',line).group())sys.stdout.write('\t')sys.stdout.write(wh_spc_len/4*'\\t'+line.rstrip().lstrip())sys.stdout.write('\\n\\\n')print'\t\\`'if__name__=='__main__':main()Thisscriptgeneratesaone-linerfrommake'spointofview.echounicodecharacter:python-cprintunichr(234)ThisscriptechosêApplyregularexpressiontolinesfromstdin[anothercommand]|python-cimportsys,re;[sys.stdout.write(re.sub('PATTERN','SUBSTITUTION',line))forlineinsys.stdin]Modifylinesfromstdinusingmappython-cimportsys;tmp=lambdax:sys.stdout.write(x.split()[0]+'\t'+str(int(x.split()[1])+1)+'\n');map(tmp,sys.stdin);DisplayListofallusersonUnix-likesystemsprint'\n'.join(line.split(:,1)[0]forlineinopen(/etc/passwd))CSVfiletojsonpython-cimportcsv,json;printjson.dumps(list(csv.reader(open('csv_file.csv'))))CompressCSSfilepython-c'importre,sys;printre.sub(\s*([{};,:])\s*,\\1,re.sub(/\*.*?\*/,,re.sub(\s+,,sys.stdin.read())))'DecodestringwritteninHexpython-cprint''.join(chr(int(''.join(i),16))foriinzip(*[iter('474e552773204e6f7420556e6978')]*2))RetrievecontenttextfromHTTPdatapython-cimportsys;printsys.stdin.read().replace('\r','').split('\n\n',2)[1];Printsfileextensionprint'~/python/one-liners.py'.split('.')[-1]EscapescontentfromstdinThiscanbeusedtoconvertastringintoaurlsafestringpython-cimporturllib,sys;printurllib.quote_plus(sys.stdin.read());Reverselinesinstdinpython-cimportsys;print'\n'.join(reversed(sys.stdin.read().split('\n')))Printtop10linesofstdinpython-cimportsys;sys.stdout.write(''.join(sys.stdin.readlines()[:10]))/path/to/your/fileSony'sOpenSourcecommandlinetoolforperformingpythononelinersusingunix-likepipesTheycallitThePyedPiperorpyp.It'sprettysimilartothe-cwayofexecutingpython,butitimportscommonmodulesandhasit'sownpresetvariablethathelpwithsplitting/joining,linecounter,etc.Youusepipestopassinformationforwardinsteadofnestedparentheses,andthenuseyournormalpythonstringandlistmethods.Hereisanexamplefromthehomepage:Here,wetakealinuxlonglisting,captureeveryotherofthe5ththroughthe10thlines,keepusernameandfilenamefields,replacehellowithgoodbye,capitalizethefirstletterofeveryword,andthenaddthetextissplendidtotheend:ls-l|pyppp[5:11:2]|whitespace[2],w[-1]|p.replace('hello','goodbye')|p.title(),'issplendid'andtheexplanation:Thisusespyp'sbuilt-instringandlistvariables(pandp

1 / 6
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功