How To Automate Using Python Ebook
How To Automate Using Python Ebook
PSW I
TCH EBOOK
How t
oAutomat
e
Usi
ngPyt
hon
How to Aut
omat e
Usi
ng Python
TABLEOFCONTENTS
[Link]
roduction( p.1)
[Link] hon( p.3)
[Link] CodeCanEnhanc eYourCareer(p.
4)
[Link] toInstallPython(p.5)
[Link]
ngSt art
edwi thPythonFuncti
ons(p.
8)
[Link]
ptingwithPyt hon( p.
11)
[Link]
on( p.12)
I
ntr
oduct
ion
Lookar ound,and youcanseePyt honcodebei ng used to
do justaboutanyt hi
[Link] 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 [Link]’
sahi gh- l
evelprogr
ammi ng
l
anguagewi t
hsi mplist
icsyntaxt hatal so boast
sal arge
l
[Link] fyou’reanI T prof essional?
Sof t
war er unst hewor l
dt hesedaysand codei show t hat
softwar ei [Link] ndustr
y,you'rebound
to usesof twar eand having evenabasi cunder st
anding
ofhow t hatsof twareisbuiltiscanbeahugeadvant age.
IT professional shavealeg up inthefir [Link]
withsof t
war eever [Link]' 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 [Link]’ llneed t o
consi dert heenvi ronmentt hatyou’ llbecodi ng/ scri
pting
[Link] 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 [Link] ffer enttypes
ofcommuni tiesf oreachscr i
pt ing l
anguagei salso an
impor tantconsi [Link]find 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
[Link]
imesi
t’
seasyt
o getcaughtup i
nthear
gument
s,butI
war
nyout
hati
tisn’
twor
thi
[Link]
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
[Link] 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
[Link],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
[Link] 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 [Link],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 [Link] 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
[Link] 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 [Link]’l
lhavemor echoi cesforhow t
o
writ
escr iptwhet heryouwantt o do i
tinPyt hon,PowerShell
,
orsomet hing el
se.
There'
sno need t
o beaPythonexpert
buthavi
ng abasicunderst
andi
ng of
thecodeishugelybenefici
al.
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 [Link] 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 [Link] det ermi
nei fyoualr
eady
havePythoni nstall
ed,fir eup yourcommand pr omptort er
mi naland
typepython- -versionorpyt hon- [Link]
swilli
mmedi at
elydisplaywhat
Pythonver si
onisi nstal
led.
However ,thisisnotent ir
[Link] i
kePower Shell,forinstance,
Pythoncanbei nstall
ed i
naf ew differentpl aces,and youmi ght
actuall
yhaveanot herversi
oninstall
ed inadi ff[Link] ng
thepyt honexecut abl
eonl yexecutesthepyt hondefined i nyourPATH
envir
onmentvar i
[Link],theali
aspyt honwi llgenerallyreferto any
[Link] [Link] 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
[Link]
hon3. xisthewayof
thefutureso we’
dliketo ensurewehavet hel
atestver
sioninst
alled
onourmachi nes.
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
.....
$ 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 [Link] i
nst
allPyt
honon
Ubunt
u16.
10 ornewer
,wecanuset
heapt
-get
packagemanager
.
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
[Link]
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
[Link] heirsi
mpl est
,funct i
onsaregr oupingsofcodet hat
perform acert ai
nt [Link]
ly,functionsaretypicallycreated whena
certai
nt askneedst o beperformed t hatrequi
resmor ethanonel ineof
[Link] 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
[Link] disani ndi
catortot hePython
int
erpreterthatsomecodei mmedi atelyfoll
owing t
hedefkeywor d wi
ll
beaf unctionand t otr
[Link] dist henalways
fol
lowed byt henameoft hef uncti
on,anopenand cl osesetof
parentheses(ifno parameters)and acolonwhi chindicatesthestartof
thebodyoft [Link]
scol onissomet imesreplaced wit
hanopen
curlybraceinot herlanguages.
def printhelloword():
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
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 [Link] ncei nourcase,wejustneed asingleparameter
,I’
ll
justadd onecall
ed [Link] 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 [Link]+oper ator“adds”each
stri
ng togethertofor mt hefinalst r
ing ofHell
o doll
y!.
def printhelloword(word):
print('Hello' + word + '!')
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
[Link] 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
[Link]
y,running
script
si naWi ndowsenvironmentisalit
tl
ebi tmor einvolvedt hanMacOS andeven
[Link]
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 [Link]
sisanexampl eofaPython
scri
ptt hatcontainssomei f/
thenlogict
odet er
minet heoperat
ingsystem we’r
e
[Link]’ 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
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int([Link]([Link](size_bytes, 1024)))
p = [Link](1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
if [Link]() == 'Windows':
import wmi
c = [Link]()
diskFreeSpace = c.win32_logicaldisk(DeviceId='C:')[0].FreeSpace
mem_bytes = c.win32_PhysicalMemory()[0].Capacity
else:
import os
diskFreeSpace = [Link]('/').f_ffree
mem_bytes = [Link]('SC_PAGE_SIZE') * [Link]('SC_PHYS_PAGES')
memory = convert_size(int(mem_bytes))
diskFreeSpace = convert_size(int(diskFreeSpace))
[Link](data)
[Link]()
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 [Link] eyou
alwaysengagewi ththePythoncommuni [Link] 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