How-to-automate-using-python-ebook.pdf

  • Uploaded by: mmm
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View How-to-automate-using-python-ebook.pdf as PDF for free.

More details

  • Words: 3,515
  • Pages: 14
AN I PSW I TCH EBOOK

How t oAut omat e Us i ngPyt hon

How t o Aut omat e Usi ng Pyt hon TABLEOFCONTENTS 1.I nt r oduct i on( p. 1) 2. WhyPyt hon( p. 3) 3.How CodeCanEnhanc eYourCar eer( p. 4) 4.How t oI ns t al lPyt hon( p. 5) 5.Get t i ngSt ar t edwi t hPyt honFunct i ons( p. 8) 6.Sc r i pt i ngwi t hPyt hon( p. 11) 7.Conc l us i on( p. 12)

I nt r oduct i on Lookar ound,and youcanseePyt honcodebei ng used t o do j ustaboutanyt hi ng.Pyt honi spopul ari nsci ent i fic fiel dsl i kedat asci ence,mat hemat i cs,and AI ,buti t ’ sj ust asheavi l yused i nsi mpl erappl i cat i onssuchasweb devel opment .Pyt honi saflexi bl el anguaget hati sbei ng used ever ywher et hesedays.I t ’ sahi ghl evelpr ogr ammi ng l anguagewi t hsi mpl i st i csynt axt hatal so boast sal ar ge l i br ar y.Butwhati fyou’ r eanI T pr of essi onal ? Sof t war er unst hewor l dt hesedaysand codei show t hat sof t war ei scr eat ed.Regar dl essofi ndust r y,you' r ebound t o usesof t war eand havi ng evenabasi cunder st andi ng ofhow t hatsof t war ei sbui l ti scanbeahugeadvant age. I T pr of essi onal shaveal eg up i nt hefir stpl ace.Wedeal wi t hsof t war eever yday.We' r eal r eadyt echi esso i t ' s goi ng t o beeasi erf orust ol ear ncodet hant hef ar mer mor ewor r i ed aboutt henextweat herpat t er nt han depl oyi ng anew pi eceofsof t war e.

How t o Aut omat eUsi ng Pyt hon

Page1

WhyPyt hon? Thi sseemsl i kesi mpl equest i on,butanswer i ng i ti s compl i cat ed. Honest l y,i ti sgoi ng t o depend onyou.You’ l lneed t o consi dert heenvi r onmentt hatyou’ l lbecodi ng/ scr i pt i ng i n.Forexampl e,i fyouar ewor ki ng i nast r i ct l yW i ndows envi r onment ,youmayoptt o usePower Shel li nst ead of Pyt hon,si nceyou’ r el i kel yal r eadyf ami l i arwi t ht he Wi ndowst er mi naland i t scommands.Thedi ffer entt ypes ofcommuni t i esf oreachscr i pt i ng l anguagei sal so an i mpor t antconsi der at i on.Maybeyoufind onel anguage’ s communi t ymor ewel comi ng t o yout hananot her . W hat everyoudo,don’ tf al li nt ot het r ap oft hi nki ng one l anguagei sbet t ert hananot her .

I t ’ snothar dt o find cont r over sywheni tcomest o whi chscr i pt i ng l anguagei st hebest .I T pr osand devel oper sal i kear edr awnt ot hei r owncommuni t i esand ar ef ever oussuppor t er soft hel anguaget hey use.Somet i mesi t ’ seasyt o getcaughtup i nt hear gument s,butI war nyout hati ti sn’ twor t hi t .Chooseascr i pt i ng l anguaget hat meet syourneeds,nott heneedsofot her s.

How t o Aut omat eUsi ng Pyt hon

Page2

W hyPyt honCont i nued. . . Eachscr i pt i ng l anguagehasi t spr osand cons, butmostcangett hesamej ob done,j usti na di ffer entway.Chooseal anguaget hatmakes senset o you. I fyouhappent o deci det ol ear nPower Shel l i nst ead,wer ecommend ourot hereBook, How To Aut omat eUsi ng Power Shel l .

I fyou’ ver ead t hi sf ar ,t henchancesar eyouar eser i ousaboutusi ng Pyt hon. You’ vemadeagr eatdeci si on.Sur e,t her ear eal otofgr eatpr ogr ammi ng l anguagesoutt her ef r om Al golt o Zeno wi t hhundr edsofl anguagesi nbet ween. ButwhyPyt hon?Forone,becausei t ' sbui l tonsi mpl esynt axand easeof i nt er pr et at i on,i ti sf ast ert o wr i t ei nand easi ert or ead t hanot herpr ogr ammi ng l anguagesl i keJava,whi chi sgood whenyou’ r epr essed f ort i me. W hi l ebot hRubyand Pyt honar eobj ect or i ent ed l anguages,Pyt hon' ssi mpl i ci t y makesi tmor efitf orscr i pt i ng.Thi si spar t i cul ar l yusef uli fyouar ewor ki ng i nI T and need t o getup and r unni ng t o aut omat et asksqui ckl y.W i t hi nt hest r uct ur e ofPyt honcode,t her ear ef astand defini t esol ut i onst o pr obl ems,maki ng i t easi erf oruser swho ar en' tpr ogr ammer s.Ruby,ont heot herhand,al l owsf or mor evar i at i oni nsol ut i ons,whi chcancausef r ust r at i ont o new user sand I T empl oyeeswho onl yneed i tf oraut omat i on. Asahi ghl evell anguage,Pyt honl anguagei sdesi gned t o beeasyt or ead and l ear nwi t houtsacr i fici ng anyofi t spower .And becausei ti sagener al pur pose pr ogr ammi ng l anguage,Pyt honhasdi ver seusesf r om web devel opmentt o compi l i ng dat aand l i stcompr ehensi on.Pyt honi sver yver sat i l e.I tmakesi teasy t or euseorext end aut omat i onr out i nes,especi al l ybecauseofanext ensi ve st andar dl i br ar yand t housandsoft hi r dpar t yl i br ar i est hr oughi t sopensour ce configur at i on.And youcanusei tt o connectot herscr i pt sand bashcommands t hatal r eadyexi sti nt hesyst em.

How t o Aut omat eUsi ng Pyt hon

Page3

How CodeCanEnhanceYourCar eer Eveni fyou’ r ewor ki ng i nI T,pr ogr ammi ng knowl edgewi l l accel er at eyourcar eerbygi vi ng youamor euni queand var i ed ski l lsett hanyourpeer s.You’ l lhavemor echoi cesf orhow t o wr i t escr i ptwhet heryouwantt o do i ti nPyt hon,Power Shel l , orsomet hi ng el se. Lear ni ng t hePyt honpr ogr ammi ng l anguagewi l lmakeyou mor esel f suffici ent .Forexampl e,whent her e’ sanaut omat i on bug,r at hert hanwai t i ng ar ound f oryourt echni calt eam t o bai l youout ,youcanhel p your sel f .Theext ensi veonl i nePyt hon communi t y,aswel last heeasi l yaccessi bl eopensour ce sof t war e,havemadei teasi ert hanevert o fixsmal lscr i pt er r or syour sel f .And i twi l lmakeyouf eelgood,i mpr essyour boss,and saveever yoneal i t t l ebi tofval uabl et i mei nt he pr ocess.

Ther e' sno need t o beaPyt honexper t buthavi ng abasi cunder st andi ng of t hecodei shugel ybenefici al .

ThePyt honl anguagecanal so hel p youi mpr oveyour col l abor at i veski l l sont hej ob.I tcanbeeasyt of eelf r ust r at ed and conf used whendeal i ng wi t hengi neer sorpr ogr ammer s, especi al l ywhenyou’ r enotal lont hesamepage.Bygai ni ng evenabasi cwor ki ng knowl edgeofpr ogr ammi ng synt ax,you canbet t erunder st and wher et hey’ r ecomi ng f r om,r at hert han j ustt heval uet hey’ r epr ovi di ng t o you.You’ l lbeabl et o t r oubl eshootaut omat i oni ssueswi t ht heabi l i t yt o pr obl em sol veand cr eat esol ut i onst hatbenefitever yone.

How t o Aut omat eUsi ng Pyt hon

Page4

How t oI nst al lPyt hon Si ncePyt honi sgener al l yused onLi nuxand MacOS,i t ’ sal so cr oss pl at f or m,so i twor ksonW i ndowsaswel l .Wewantt o ensur ewe’ r e abl et o usePyt honr egar dl essoft heoper at i ng syst em we’ r eusi ng,so l et ’ sgo overhow t o getPyt honup and r unni ng onbot hW i ndowsand Li nux/MacOS.

Det er mi ni ng Cur r ent l yI nst al l ed Ver si on Unl i keW i ndows,Pyt hont ypi cal l ycomespr ei nst al l ed onmany* ni x oper at i ng syst emsand MacOS.To det er mi nei fyoual r eady havePyt honi nst al l ed,fir eup yourcommand pr omptort er mi naland t ypepyt honver si onorpyt honV.Thi swi l li mmedi at el ydi spl aywhat Pyt honver si oni si nst al l ed. However ,t hi si snotent i r el yaccur at e.Unl i kePower Shel l ,f ori nst ance, Pyt honcanbei nst al l ed i naf ew di ffer entpl aces,and youmi ght act ual l yhaveanot herver si oni nst al l ed i nadi ffer entdi r ect or y.Runni ng t hepyt honexecut abl eonl yexecut est hepyt hondefined i nyourPATH envi r onmentvar i abl e.Al so,t heal i aspyt honwi l lgener al l yr ef ert o any 2. xver si on.I fyouhavePyt hon3. xi nst al l ed,youwi l lal so havet he pyt hon3al i as. Youcanseebel ow t hatbot h2. 7. 1 0 and 3. 6. 2ar ei nst al l ed.

$ python -V Python 2.7.10 $ python --version Python 2.7.10 $ python3 --version Python 3.6.2 $ python3 -V Python 3.6.2 How t o Aut omat eUsi ng Pyt hon

Page5

I nst al l i ng Pyt hononMacOS Event hought her eseemst o beal otofcodest i l loutt her er unni ng 2. x,pyt hon2i ssl owl ybecomi ng obsol et e.Pyt hon3. xi st hewayof t hef ut ur eso we’ dl i ket o ensur ewehavet hel at estver si oni nst al l ed onourmachi nes. OnMacOS,t her ecommended wayt o getPyt hon3. xonyour machi nei st o uset heHomeBr ew ut i l i t y.HomeBr ew i sapackage managersi mi l art ot hePower Shel lGal l er yt hatal l owsuser st o downl oad and i nst al lpr ogr amsf r om apubl i cr eposi t or y.

Youcanseeher et hatHomeBr ew al r eadyknew t hatIhad anol der ver si onofPyt hon3i nst al l ed and pr ompt ed met o upgr ade. $ brew install python3 Updating Homebrew... ==> Auto-updated Homebrew! Updated 1 tap (homebrew/core). ==> New Formulae .....

Inow havePyt hon3. 6. 2i nst al l ed and am up t o dat e!

Error: python3 3.6.0 is already installed To upgrade to 3.6.2, run `brew upgrade python3` $ brew upgrade python3 ==> Upgrading 1 outdated package, with result: python3 3.6.2 ==> Upgrading python3 ==> Installing dependencies for python3: readline, sqlite, gdbm, openssl ...... ==> Summary /usr/local/Cellar/python3/3.6.2: 3,598 files, 55.9MB $ python3 Python 3.6.2 (v3.6.2:5fd33b5926, Jul 16 2017, 20:11:06) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information.

How t o Aut omat eUsi ng Pyt hon

Page6

I nst al l i ng Pyt hononLi nux I nst al l i ng Pyt hononLi nuxi sal so j ustas st r ai ght f or war d asMacOS.To i nst al lPyt honon Ubunt u1 6. 1 0 ornewer ,wecanuset heapt get packagemanager . $ sudo apt-get update

I nFedor a,wecoul d do:

$ sudo apt-get install python3.6

$ sudo dnf install python3

I nst al l i ng Pyt hononW i ndows I nst al l i ng Pyt hononW i ndowsi sasst r ai ght f or war d as anyst andar d MSIpackageyou’ r eused t oi nst al l i ng. Si nceW i ndowsdoesn’ thavePyt honi nst al l ed bydef aul t , t hi si samust .You’ l lfir stneed t o head overt ot he Wi ndowsdownl oad sect i ononpyt hon. or g and gr ab t he appr opr i at ei nst al l er .Justscr ol lovert o downl oadsand cl i ckPyt hon3. 6. 4f orW i ndows.

How t o Aut omat eUsi ng Pyt hon

Page7

Get t i ng St ar t ed wi t hPyt honFunct i ons Aswi t hj ustaboutever ypr ogr ammi ng l anguage,Pyt honhasaconcept cal l ed f unct i ons.Att hei rsi mpl est ,f unct i onsar egr oupi ngsofcodet hat per f or m acer t ai nt ask.Typi cal l y,f unct i onsar et ypi cal l ycr eat ed whena cer t ai nt askneedst o beper f or med t hatr equi r esmor et hanonel i neof code.Funct i onsar eagr eatwayt o packageup mul t i pl el i nesofcode whi cht henpr ovi dest heuseraneasywayt or unal loft hatcodeatonce i nst ead oft ypi ng eachl i ne,hi t t i ng Ent erand r epeat i ng. I nPyt hon,af unct i oni scr eat ed byusi ng t hedefkeywor d whi chcr eat es af unct i ondefini t i on.Thedefkeywor di sani ndi cat ort ot hePyt hon i nt er pr et ert hatsomecodei mmedi at el yf ol l owi ng t hedefkeywor d wi l l beaf unct i onand t ot r eati tl i ket hat .Thedefkeywor di st henal ways f ol l owed byt henameoft hef unct i on,anopenand cl osesetof par ent heses( i fno par amet er s)and acol onwhi chi ndi cat est hest ar tof t hebodyoft hef unct i on.Thi scol oni ssomet i mesr epl aced wi t hanopen cur l ybr acei not herl anguages.

def printhelloword(): We’ vecr eat ed ourfir stf unct i on!Hi tEnt er ,and i tdoesabsol ut el ynot hi ng. Let ’ sadd somecodei nsi deoft hef unct i ont o act ual l ymaket hi seffor t wor t hwhi l e.To bui l dt hef unct i on’ scode,weneed t oi ndentt henext i mmedi at el i nebyatl eastonespaceal t houghf ourspacesorasi ngl et ab i scommon.To t hedi smayorsome,Pyt honuseswhi t espacet o del i neat e var i ousconst r uct si nt hel anguage.So,f orexampl e,i fyouwantmy pr i nt hel l owor d( )f unct i ont o pr i ntt hephr ase,“ Hel l o,wor l d! ”wheni t ’ sr un, youcoul di ndentt henextl i neand add apr i nt ( )r ef er ence.

def printhelloword():

print('Hello world!')

How t o Aut omat eUsi ng Pyt hon

Page8

Oncedefined,youcant hencal lt hi sf unct i onwi t hpr i nt hel l owor l d( ) . def printhelloword(): print('Hello world!') printhelloword() Hello world! However ,i fyoudon’ ti ncl udet hatwhi t espacebef or et hepr i nt ( )r ef er ence, youwoul d getasynt axer r orso r emembert oi ndent ! def printhelloword(): print('Hello world!') print('Hello world!') ^ IndentationError: expected an indented block

We’ venow cr eat edourf i r stf unct i on,butwhati fIdon’ t al wayswantt opr i ntt hest r i ng,“ Hel l owor l d! ”Per haps I ’ dl i ket or et ur n,“ Hel l odol l y! ”i nst ead.I nt hatcase,I needt oi nt r oduceapar amet ert omyf unct i on.A par amet eri sawayt opr ovi deani nputt oyourf unct i on. Apar amet eral l owsyout opassdi f f er entval uesi nt oyour f unct i ont ot henbepr ocessedi nsi deoft hef unct i on.I n ourcase,Iwantt heabi l i t yt ochanget hest r i ngwor l d wi t hwhat everwor dIwantwhent hef unct i oni sexecut ed.

How t o Aut omat eUsi ng Pyt hon

Page9

Cr eat i ng Par amet er si nPyt hon To cr eat eapar amet er ,wecr eat eavar i abl ei nsi deoft hef unct i on’ spar ent heses separ at ed byacomma.Si ncei nourcase,wej ustneed asi ngl epar amet er ,I ’ l l j ustadd onecal l ed wor d.It henneed t or epl acemyst at i cr ef er encet ot he wor d" wor l d"and i nst ead r epl acei twi t ht hepar amet ervar i abl e. To r epl acet hest at i cwor l dr ef er ence,not i cet hatIhad t o cr eat et hr ee“ gr oups” ; ' Hel l o' ,wor d and ' ! ' .Thi si scal l ed st r i ng concat enat i onand i sonemet hod of i nser t i ng avar i abl ei nsi deofast r i ng i nPyt hon.The+oper at or“ adds”each st r i ng t oget hert of or mt hefinalst r i ng ofHel l o dol l y! .

def printhelloword(word): print('Hello' + word + '!') Oncewe’ veadded t hepar amet er ,wecant hencal lt hef unct i onagai n,but i nst ead ofj ustappendi ng anopenand cl osepar ent hesesaf t ert hef unct i on name,wecani nser tt hepar amet erar gument .Thepar amet erar gumenti st he val ueoft hepar amet eratr unt i me. printhelloword('dolly') Hello dolly!

How t o Aut omat eUsi ng Pyt hon

Page1 0

Scr i pt i ngwi t hPyt hon Now t hatyouhaveabasi cuder st andi ngofhow t hesynt axandf unct i onswor ki n Pyt hon.l et scoveracoupl eofscr i pt st ogi veyouani deaofhow Pyt honcanhel pyou aut omat esi mpl eI Tt asks.Asyougetmor ecomf or t abl ewi t hPyt hon,youwi l lwantt o j umpi nt omor er esour cesonl i net ocr eat emor ecompl exscr i pt s. Butbef or ewest ar twi t hscr i pt s,i ti si mpor t antt onot eagai nt hedi f f er encesbet ween i nst al l i ngPyt hononWi ndows,MacOs,andLi nuxdi st r i but i ons.Speci f i cal l y ,r unni ng scr i pt si naWi ndowsenvi r onmenti sal i t t l ebi tmor ei nvol vedt hanMacOS andeven Li nux. Forbr evi t y ,wewon’ tj umpi nt odet ai lher e,butt her ear epl ent yofdet ai l sonl i ne t hatdi vei nt oI DEs,suchasPyChar m,t hePyt honshel l ,andhow t or unscr i pt son Wi ndows. Thef i r stscr i ptwe’ l lcoverher ewi l lhel pyougetsomebasi ci nf oonamachi ne. Not i cet her ei sanexcept i onf orWi ndowsmachi nes.Thi si sanexampl eofaPyt hon scr i ptt hatcont ai nssomei f / t henl ogi ct odet er mi net heoper at i ngsyst em we’ r e r unni ngon.You’ l lhavet odot hi ssomet i mesi fyou’ r ecr eat i ngcr osspl at f or m scr i pt s meani ngaPyt honscr i ptt hatwi l lr unondi f f er entoper at i ngsyst ems. Thi spar t i cul arscr i ptgr abssomei mpor t anti nf or mat i onf r om t hesyst em i t ’ sr unni ng onandwr i t esi tt oaCSV f i l e-acommonI Tadmi nt ask. import csv import platform import math csvFile = open('OSInformation.csv', "w") writer = csv.writer(csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return "%s %s" % (s, size_name[i]) if platform.system() == 'Windows': import wmi c = wmi.WMI() diskFreeSpace = c.win32_logicaldisk(DeviceId='C:')[0].FreeSpace mem_bytes = c.win32_PhysicalMemory()[0].Capacity else: import os diskFreeSpace = os.statvfs('/').f_ffree mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') osVer = '{0} {1}'.format(platform.system(), platform.release()) memory = convert_size(int(mem_bytes)) diskFreeSpace = convert_size(int(diskFreeSpace)) data = [['DiskFreeSpace', 'OSVersion', 'TotalMemory'], [diskFreeSpace, osVer, memory]] writer.writerows(data) csvFile.close() How t o Aut omat eUsi ng Pyt hon

Page1 1

Youshoul dnow haveaf oundat i onf oraut omat i ngi nPyt hon.I hopet hatyouf oundt hi smat er i alhel pf ulandcont i nuet odi scover new wayst oaut omat eyourj obi nI T. I fyouwantt ocont i nueyourscr i pt i ngj our ney ,t her e’ savastamountof cont entavai l abl eonl i neawai t i ngyourcust om.Andmakesur eyou al waysengagewi t ht hePyt honcommuni t y .Thecommuni t yi sknown f orbei nghi ghl yaccept i ngofnewbi es, sodon’ tbeaf r ai dt oaskf or hel pt her e. Happyscr i pt i ng!

Lear nmor eabouthow I pswi t chcanhel p youand yourI Tt eam. Vi si twww. i pswi t ch. com

More Documents from "mmm"