Вы находитесь на странице: 1из 14

AN I

PSW I
TCH EBOOK

How t
oAutomat
e
Usi
ngPyt
hon
How to Aut
omat e
Usi
ng Python

TABLEOFCONTENTS
1.Int
roduction( p.1)
2.WhyPyt hon( p.3)
3.How CodeCanEnhanc eYourCareer(p.
4)
4.How toInstallPython(p.5)
5.Getti
ngSt art
edwi thPythonFuncti
ons(p.
8)
6.Scri
ptingwithPyt hon( p.
11)
7.Conclusi
on( p.12)
I
ntr
oduct
ion
Lookar ound,and youcanseePyt honcodebei ng used to
do justaboutanyt hi
ng.Pyt honi spopul arinscient
ific
fieldslikedatascience,mat hemat ics,and AI ,butit’sjust
asheavi l
yused insimpl erappli
cat ionssuchasweb
development .Pythonisaflexi blel anguaget hatisbeing
used everywheret hesedays.It’
sahi gh- l
evelprogr
ammi ng
l
anguagewi t
hsi mplist
icsyntaxt hatal so boast
sal arge
l
ibrary.Butwhati fyou’reanI T prof essional?

Sof t
war er unst hewor l
dt hesedaysand codei show t hat
softwar ei screated.Regardlessofi ndustr
y,you'rebound
to usesof twar eand having evenabasi cunder st
anding
ofhow t hatsof twareisbuiltiscanbeahugeadvant age.
IT professional shavealeg up inthefir stplace.Wedeal
withsof t
war eever yday.We' realreadytechiesso i
t's
going to beeasi erforustol ear
ncodet hant hefar
mer
mor ewor ried aboutthenextweat herpatternthan
depl oying anew pi eceofsof tware.

How t
o Aut
omat
eUsi
ng Pyt
hon Page1
WhyPyt
hon?
Thi
sseemsli
kesi
mpl
equest
ion,butanswer
ing i
tis
compl
icat
ed.

Honest l
y,itisgoi ng to depend onyou.You’ llneed t o
consi dert heenvi ronmentt hatyou’ llbecodi ng/ scri
pting
in.Forexampl e,ifyouar ewor king i
nast ri
ctlyW i ndows
envi r
onment ,youmayoptt o usePower Shel linstead of
Pyt hon,sinceyou’ rel ikelyalreadyf amili
arwi ththe
Wi ndowst ermi naland i tscommands.Thedi ffer enttypes
ofcommuni tiesf oreachscr i
pt ing l
anguagei salso an
impor tantconsi deration.Maybeyoufind onel anguage’ s
communi t
ymor ewel comi ng to yout hananot her .
W hat everyoudo,don’ tfalli
nt ot hetrap ofthinking one
languagei sbet tert hananot her .

I
t’snothar
dto find cont
rover
sywheni
tcomest
o whi
chscr
ipt
ing
l
anguagei
sthebest
.IT pr
osand devel
oper
sal
ikear
edr
awnt
othei
r
owncommuni
tiesand ar
efever
oussuppor
ter
soft
hel
anguaget
hey
use.Somet
imesi
t’
seasyt
o getcaughtup i
nthear
gument
s,butI
war
nyout
hati
tisn’
twor
thi
t.Chooseascr
ipt
ing l
anguaget
hat
meet
syourneeds,nott
heneedsofot
her
s.

How t
o Aut
omat
eUsi
ng Pyt
hon Page2
W hyPyt
honCont
inued.
..
Eachscripti
ng l
anguagehasitsprosand cons,
butmostcangett hesamejob done,justi
na
differ
entway.Chooseal anguaget hatmakes
senseto you.

I
fyouhappent o deci
det olear
nPower Shel
l
i
nst
ead,wer ecommend ourot hereBook,
How To Aut
omateUsi ng PowerShel
l.

Ifyou’veread t
hisfar,thenchancesar eyouar eseri
ousaboutusi ng Python.
You’vemadeagr eatdeci si
on.Sure,t her
ear ealotofgr eatprogrammi ng
l
anguagesoutt herefr
om Al golto Zeno withhundredsofl anguagesinbet ween.
ButwhyPyt hon?Forone,becausei t
'sbuil
tonsi mplesynt axand easeof
i
nt er
pretati
on,itisfasterto wri
tei nand easi
ertor ead t
hanot herprogrammi ng
l
anguagesl ikeJava,whi chisgood whenyou’ r
epr essed f
ortime.

W hi
lebothRubyand Pyt honar eobject-oriented l
anguages,Pyt hon'
ssi mplici
ty
makesi tmor efitforscri
pt i
ng.Thisispar t
icularl
yusef ulifyouar eworking inIT
and need t
o getup and running t
o automat etasksqui ckly.W it
hinthest ructure
ofPythoncode,t herearef astand definitesolutionst o problems,maki ng i
t
easi
erforuser swho aren'tprogrammer s.Ruby,ont heot herhand,al l
owsf or
morevar i
ationinsolut
ions,whi chcancausef rustr
ationt o new usersand IT
employeeswho onl yneed itforautomat i
on.

Asahi gh- l
evellanguage,Pyt honl anguagei sdesigned t o beeasyt oread and
learnwi t
houtsacr i
ficing anyofi tspower .And becausei tisagener al
-purpose
programmi ng language,Pythonhasdi verseusesf r
om web devel opmentto
compi l
ing dataand li
stcompr ehension.Pyt honisver yver sat
ile.I
tmakesi teasy
toreuseorext end automat i
onr outi
nes,especi al
lybecauseofanext ensi
ve
standardl i
braryand thousandsoft hir
d- partyl
ibrariesthroughi tsopen-source
configur ati
on.And youcanusei tto connectot herscr i
ptsand bashcommands
thatalreadyexi sti
nthesyst em.

How t
o Aut
omat
eUsi
ng Pyt
hon Page3
How CodeCanEnhanceYourCar
eer

Eveni fyou’r
ewor king inIT,programmi ng knowl edgewil
l
accelerat
eyourcar eerbygi vi
ng youamor euni queand var
ied
ski
llsetthanyourpeer s.You’l
lhavemor echoi cesforhow t
o
writ
escr iptwhet heryouwantt o do i
tinPyt hon,PowerShell
,
orsomet hing el
se.

Learning thePyt honpr ogrammi ng l


anguagewi l
lmakeyou
mor eself-sufficient.Forexampl e,whent here’
sanaut omation
bug,r at
hert hanwai t
ing around f oryourt echnicalteam to bai
l
youout ,youcanhel p yourself.Theext ensiveonlinePyt hon
communi t
y,aswel last heeasi lyaccessibleopen- source
software,havemadei teasi ert hanevert o fixsmal lscri
pt
errorsyour sel
f.And i
twi llmakeyouf eelgood,i mpressyour
boss,and saveever yoneal it
tlebi tofvaluablet i
mei nthe
process.

There'
sno need t
o beaPythonexpert
buthavi
ng abasicunderst
andi
ng of
thecodeishugelybenefici
al.

ThePyt honl anguagecanal so help youimpr oveyour


collaborativeskil
lsont hejob.Itcanbeeasyt of eelfrustr
ated
and conf used whendeal i
ng withengi neersorpr ogrammer s,
especiallywhenyou’ r
enotal lont hesamepage.Bygai ni
ng
evenabasi cwor king knowl edgeofpr ogrammi ng syntax,you
canbet terunder stand wher ethey’ recomi ng fr
om,r atherthan
justtheval uethey’repr oviding to you.You’llbeabl eto
troubleshootaut omat ionissueswi t htheabi l
ityto problem
solveand cr eatesolutionst hatbenefitever yone.

How t
o Aut
omat
eUsi
ng Pyt
hon Page4
How t
oInst
allPyt
hon
SincePyt honisgeneral
lyused onLinuxand MacOS,i t’
salso cr
oss
platform,so itworksonW indowsaswel l.Wewantt o ensur
ewe’ re
ablet o usePythonregardlessoftheoperati
ng syst
em we’ reusing,so
l
et ’
sgo overhow t o getPythonup and r
unning onbot hW indowsand
Li
nux/MacOS.

Det
ermi
ning Cur
rent
lyI
nst
all
ed Ver
sion
Unli
keW indows,Pyt hont ypi
call
ycomespr e-inst
all
ed onmany* ni
x
operat
ing systemsand MacOS.To det ermi
nei fyoualr
eady
havePythoni nstall
ed,fir eup yourcommand pr omptort er
mi naland
typepython- -versionorpyt hon- V.Thi
swilli
mmedi at
elydisplaywhat
Pythonver si
onisi nstal
led.

However ,thisisnotent ir
elyaccurate.Unl i
kePower Shell,forinstance,
Pythoncanbei nstall
ed i
naf ew differentpl aces,and youmi ght
actuall
yhaveanot herversi
oninstall
ed inadi fferentdirectory.Runni ng
thepyt honexecut abl
eonl yexecutesthepyt hondefined i nyourPATH
envir
onmentvar i
able.Also,theali
aspyt honwi llgenerallyreferto any
2.xversion.IfyouhavePyt hon3.xi nst
alled,youwi l
lalso havet he
python3al ias.

Youcanseebel
ow t
hatbot
h2.
7.1
0 and 3.
6.2ar
einst
all
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
all
ing Pyt
hononMacOS
Event houghthereseemst o beal otofcodestil
loutthererunning
2.x,python2isslowlybecomi ng obsol
ete.Pyt
hon3. xisthewayof
thefutureso we’
dliketo ensurewehavet hel
atestver
sioninst
alled
onourmachi nes.

OnMacOS,t her ecommended wayto getPython3. xonyour


machi
neisto uset heHomeBrew uti
li
ty.HomeBr ew isapackage
managersi
mi l
art othePowerShel
lGaller
ythatal l
owsusersto
downl
oad and instal
lpr
ogramsfrom apubli
cr epositor
y.

Youcanseeher ethatHomeBr ew
alr
eadyknew thatIhad anol der
versi
onofPython3i nstal
led and
prompt
ed met o upgrade.

Inow havePyt
hon3. 6.
2instal
led and
$ brew install python3
am up t
o date!
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
.....

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
all
ing Pyt
hononLi
nux
I
nst
all
ing Pyt
hononLi
nuxi
sal
so j
ustas
st
rai
ght
for
war
d asMacOS.To i
nst
allPyt
honon
Ubunt
u16.
10 ornewer
,wecanuset
heapt
-get
packagemanager
.

$ sudo apt-get update

$ sudo apt-get install python3.6


I
nFedor
a,wecoul
d do:

$ sudo dnf install python3

I
nst
all
ing Pyt
hononW i
ndows

I
nst
all
ing Pyt
hononW i
ndowsi
sasst
rai
ght
for
war
d as
anyst
andar
d MSIpackageyou’
reused t
oinst
all
ing.
Si
nceW i
ndowsdoesn’
thavePyt
honi
nst
all
ed bydef
aul
t,
t
hisi
samust
.You’
llfir
stneed t
o head overt
othe
Wi
ndowsdownl
oad sect
iononpyt
hon.
org and gr
ab t
he
appr
opr
iat
einst
all
er.Justscr
ollovert
o downl
oadsand
cl
ickPyt
hon3.
6.4f
orW i
ndows.

How t
o Aut
omat
eUsi
ng Pyt
hon Page7
Get
ting St
art
ed wi
thPyt
honFunct
ions
Aswi thjustaboutever yprogrammi ng l
anguage,Pyt honhasaconcept
call
ed functi
ons.Att heirsi
mpl est
,funct i
onsaregr oupingsofcodet hat
perform acert ai
nt ask.Typical
ly,functionsaretypicallycreated whena
certai
nt askneedst o beperformed t hatrequi
resmor ethanonel ineof
code.Funct i
onsar eagr eatwayt o packageup mul tiplelinesofcode
whicht henpr ovidest heuseraneasywayt orunal loft hatcodeatonce
inst
ead oftypi ng eachline,hit
ting Enterand repeati
ng.
InPython,af unctioniscreat
ed byusi ng thedefkeywor d whi
chcr eat
es
afunctiondefini ti
on.Thedefkeywor disani ndi
catortot hePython
int
erpreterthatsomecodei mmedi atelyfoll
owing t
hedefkeywor d wi
ll
beaf unctionand t otr
eatitlikethat.Thedefkeywor dist henalways
fol
lowed byt henameoft hef uncti
on,anopenand cl osesetof
parentheses(ifno parameters)and acolonwhi chindicatesthestartof
thebodyoft hefunction.Thi
scol onissomet imesreplaced wit
hanopen
curlybraceinot herlanguages.

def printhelloword():

We’vecreated ourfirstf uncti


on!HitEnter,and i tdoesabsol utelynothing.
Let’
sadd somecodei nsideoft hefunctiont o actuallymaket hiseffor t
worthwhil
e.To buil
dt hef uncti
on’scode,weneed t oi ndentt henext
immediateli
nebyatl eastonespaceal thoughf ourspacesorasi ngl
et ab
iscommon.To t hedismayorsome,Pyt honuseswhi tespacet o deli
neate
vari
ousconstructsint helanguage.So,forexampl e,ifyouwantmy
pri
nthel
loword()funct i
ont o pri
ntthephr ase,“ Hello,wor l
d!”wheni t’
srun,
youcouldindentt henextl ineand add apr i
nt( )reference.

def printhelloword():
print('Hello world!')

How t
o Aut
omat
eUsi
ng Pyt
hon Page8
Oncedefined,youcant
hencal
lthi
sfunct
ionwi
thpr
int
hel
lowor
ld(
).

def printhelloword():
print('Hello world!')

printhelloword()
Hello world!

However
,ifyoudon’tincl
udet hatwhi
tespacebef
orethepr
int
()r
efer
ence,
youwould getasynt
axer rorso r
emembert oi
ndent
!

def printhelloword():
print('Hello world!')

print('Hello world!')
^
IndentationError: expected an indented block

We’ venow cr eatedourf i


rstfuncti
on,butwhati fIdon’t
alwayswantt opr intt
hest r
ing,“Hellowor l
d!”Perhaps
I’
dliketor eturn,“Hellodol ly!”i
nstead.I nthatcase,I
needt ointroduceapar amet ertomyf unct
ion.A
parameteri sawayt opr ovideani nputt oyourfuncti
on.
Apar amet erallowsyout opassdi fferentvaluesintoyour
functi
ontot henbepr ocessedi nsi
deoft hefuncti
on.In
ourcase,Iwantt heabi li
tytochanget hest r
ingworld
withwhat everwor dIwantwhent hef uncti
oni sexecuted.

How t
o Aut
omat
eUsi
ng Pyt
hon Page9
Cr
eat
ing Par
amet
ersi
nPyt
hon
To createaparameter
,wecr eat eavari
ableinsi
deoft hefuncti
on’sparent
heses
separated byacomma.Si ncei nourcase,wejustneed asingleparameter
,I’
ll
justadd onecall
ed word.Ithenneed toreplacemyst ati
creferencetothe
wor d"world"and i
nst
ead replaceitwit
ht heparametervariabl
e.

To replacet
hest ati
cwor ldref
erence,not i
cet hatIhad t
o createthree“groups”
;
'Hello'
,word and '
!'
.Thisi scal
led stri
ng concatenati
onand isonemet hod of
inserti
ng avariabl
ei nsi
deofast r
ing inPython.The+oper ator“adds”each
stri
ng togethertofor mt hefinalst r
ing ofHell
o doll
y!.

def printhelloword(word):
print('Hello' + word + '!')

Oncewe’ veadded thepar amet er


,wecant hencallthefunct
ionagain,but
instead ofj
ustappendi ng anopenand closepar ent
hesesafterthef
unction
name,wecani nsertt hepar ameterar
gument .Theparameterargumentisthe
valueoft heparamet eratr unti
me.

printhelloword('dolly')
Hello dolly!

How t
o Aut
omat
eUsi
ng Pyt
hon Page1
0
Scr
ipt
ingwi
thPyt
hon
Now t
hatyouhaveabasicuderst
andingofhow t
hesyntaxandf uncti
onsworki
n
Pyt
hon.l
etscoveracoupleofscr
ipt
st ogi
veyouani deaofhow Pythoncanhelpyou
aut
omatesimpl
eITtasks.Asyougetmor ecomfort
ablewit
hPyt hon,youwi
llwantt
o
j
umpintomoreresour
cesonli
netocreatemorecompl exscri
pts.
Butbef orewest ar
twit
hscr i
pts,i
tisimportantt onoteagaint hediff
er encesbet ween
i
nst al
li
ngPyt hononWi ndows,MacOs,andLi nuxdi st
ribut
ions.Specificall
y,running
script
si naWi ndowsenvironmentisalit
tl
ebi tmor einvolvedt hanMacOS andeven
Linux.Forbrevit
y,wewon’ tj
umpi nt
odetailher e,buttherearepl entyofdet ail
sonline
thatdiveint
oI DEs,suchasPyChar m,thePyt honshel l
,andhow t or unscr i
ptson
Wi ndows.
Thef ir
stscriptwe’ l
lcoverherewi l
lhel
pyougetsomebasi cinfoonamachi ne.
Noticet her
ei sanexcept i
onf orWindowsmachi nes.Thi
sisanexampl eofaPython
scri
ptt hatcontainssomei f/
thenlogict
odet er
minet heoperat
ingsystem we’r
e
runningon.You’ l
lhavetodot hissometimesifyou’r
ecreati
ngcr oss-
plat
for
m scri
pts
meani ngaPyt honscriptt
hatwi l
lrunondiff
erentoperat
ingsystems.
Thi
spar
ti
cularscr
iptgr
abssomei
mpor
tanti
nfor
mat
ionf
rom t
hesyst
em i
t’
srunni
ng
onandwri
tesitt
oaCSV fil
e-acommonITadmint
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 haveafoundati
onf orautomati
nginPyt
hon.I
hopethatyouf
oundthismater
ialhelpfulandconti
nuet
odiscover
new wayst
oautomat eyourj obi
nIT.
I
fyouwantt ocontinueyourscr
ipti
ngj ourney,there’
savastamountof
contentavai
lableonli
neawaiti
ngyourcust om.Andmakesur eyou
alwaysengagewi ththePythoncommuni ty.Thecommuni t
yisknown
forbeinghighlyaccepti
ngofnewbi es,sodon’ tbeafr
aidt
oaskfor
helpthere.
Happyscr
ipt
ing!

Lear
nmor eabouthow I
pswi
tchcanhel
p
youand yourI
Tteam.
Vi
sitwww.
ipswi
tch.
com

Вам также может понравиться