May 28-30, 2018 Vikrant Patil
These notes are available online at http://notes.pipal.in/2018/vmware-advanced-may
© Pipal Academy LLP
We will be using anaconda (python 3) distribution for this training. it can be downloaded from
import requests
def download(url):
r = requests.get(url)
return r
Handling Exceptions
try:
a = int(input("Enter some integer:"))
except ValueError as v:
print(v)
print("Integer value expected...")
try:
a = int(input("Enter some integer:"))
except ValueError as v:
print(v)
print("Integer value expected...")
except RuntimeError:
pass
except Exception:
pass
else:
# executed only if no exception occurs
pass
finally:
#will be executed compulsory irrespective of whether exception occurs
# or not
pass
def raiselist():
raise []
try:
raiselist()
except list as l:
print(l)
try:
raiselist()
except TypeError as t:
print(t)
l = []
l[1]
try:
l[1]
except IndexError as e:
print(e)
problem
with_retries which tries to call function five times. and gives up after that.from urllib.request import urlopen
@with_retries
def download(url):
r = urlopen(url)
return r
download("http://google.com/nosuchurl")
failed -- 1 retrying
failed -- 1 retrying
failed -- 1 retrying
failed -- 1 retrying
failed -- 1 retrying
giving up!
timeit which times given function. make use of time module@timeit
def foo():
...
...
foo()
Time taken to execute foo = 2.0 seconds
import time
time.time()
import time
def with_retries(func):
def wrapper(*args):
for i in range(5):
try:
return func(*args)
except Exception as e:
print(e, "Retrying")
time.sleep(1)
print("Giving up!")
return wrapper
from urllib.request import urlopen
@with_retries
def download(url):
return urlopen(url)
download("http://googl.com/nosuchurl.ksjdlkaj")
from urllib.request import urlopen
@with_retries(tries=5, wait=1)
def download(url):
return urlopen(url)
@vm_running(vmparameters..)
def get_some_info_from_vm():
pass
def with_retries(tries=5, wait=0.5):
def decor(func):
def wrapper(*args):
for i in range(tries):
try:
return func(*args)
except Exception as e:
print(e, "retrying...")
time.sleep(wait)
print("Giving up!")
return wrapper
return decor
from urllib.request import urlopen
@with_retries(tries=2, wait=1)
def download(url):
return urlopen(url)
download("http://google.com/xkjhfdshfh")
download()
import functools
#functools.partial()
def foo(a,b,c):
pass
foo1 = functools.partial(foo, 2,3)
foo1
foo1(4)
def foo(a,b,c):
return a+b+c
f = functools.partial(foo, 3, 4)
f(5)
%%file functions.py
def cat(file):
with open(file) as f:
print(f.read())
def head(file, n):
with open(file) as f:
for i in range(int(n)):
print(f.readline(), end="")
def grep(pattern, file):
with open(file) as f:
for line in f:
if pattern in line:
print(line, end="")
%%file commands.py
import sys
commandcache = {}
def command(func):
commandcache[func.__name__] = func
return func
def help_():
print("Available commands are..")
for cmd in commandcache:
f = commandcache[cmd]
print("{cmd}:{doc}".format(cmd=cmd, doc=f.__doc__))
def main():
cmd = sys.argv[1]
if cmd in commandcache:
commandcache[cmd](*sys.argv[2:])
else:
print("Invalid command,",cmd)
help_()
%%file functions.py
from commands import command, main
@command
def cat(file):
"""
cat filename .. displays file contents
"""
with open(file) as f:
print(f.read())
@command
def head(file, n):
"""
head filename n .. displays first n lines of file
"""
with open(file) as f:
for i in range(int(n)):
print(f.readline(), end="")
def grep(pattern, file):
with open(file) as f:
for line in f:
if pattern in line:
print(line, end="")
if __name__ == "__main__":
main()
!python functions.py cat tables.csv
!python functions.py head tables.csv 2
!python functions.py grep hello tables.csv
Just observe for loop in python
for n in range(5):
print(n)
for c in "string":
print(c)
numbers = range(5)
nums = iter(range(5))
type(nums)
next(nums)
next(nums)
next(nums)
next(nums)
next(nums)
next(nums)
def digits(n):
while n >= 0:
yield n
n -= 1
def digits(n):
print("start digits...")
while n >= 0:
print("before yield")
yield n
print("after yield")
n -= 1
print("after while loop")
d = digits(5)
type(d)
next(d)
next(d)
next(d)
next(d)
next(d)
next(d)
next(d)
for d in digits(3):
print(d)
d = digits(2)
next(d)
next(d)
next(d)
next(d)
next(d)
list(digits(2))
problem
e = evens(10)
for i in e:
print(i, end=",")
0,2,4,6,8
take that consumes n elements from sequence and returns those as a list.e = evens(20)
take(e, 5)
[0,2,4,6,8]
def evens(n):
for i in range(2,n,2):
yield i
def take(seq, n):
return [next(seq) for i in range(n)]
take(evens(1000), 5)
e = evens(20)
take(e, 5)
for i in e:
print(i, end=",")
e = (i for i in range(1000) if i%2==0)
type(e)
next(e)
sum(e)
type(e)
sum(e)
e = (i for i in range(1000) if i%2==0)
max(e)
def integers():
n = 0
while True:
yield n
n += 1
naturals = integers()
type(naturals)
next(naturals)
next(naturals)
sum(take(naturals, 10))
coimport time
from functools import partial
def with_retries(f=None, retries=5, delay=0):
if f == None:
return partial(with_retries, retries=retries, delay=delay)
def g(*args):
print("retries = ",retries,"delay=", delay)
for i in range(retries):
try:
return f(*args)
except Exception as e:
print(f.__name__, args, "failed:", e)
time.sleep(delay)
print("Giving up...")
return g
@with_retries(retries=2, delay=1)
def download():
pass
With generators and iterators
import os
def find(path):
for dirpath, dirname, files in os.walk(path):
for f in files:
yield os.path.join(dirpath, f)
def take(seq, n):
return [next(seq) for i in range(n)]
files = find("/home/vikrant/programming/explorations/python")
take(files, 5)
def grep(pattern, seq):
for item in seq:
if pattern in item:
yield item
files = find(".")
pyfiles = grep(".py", files)
take(pyfiles, 5)
def readlines(files):
for f in files:
with open(f) as fd:
for line in fd:
yield line
files = find(".")
pyfiles = grep(".py", files)
lines = readlines(pyfiles)
funcs = grep("def ", lines)
take(funcs, 5)
def count(seq):
return sum(1 for i in seq)
files = find(".")
pyfiles = grep(".py", files)
lines = readlines(pyfiles)
funcs = grep("def ", lines)
count(funcs)
import re
def grep(pattern, seq):
p = re.compile(pattern)
for item in seq:
if p.match(item):
yield item
p = grep(".*\.py$", ["hello.py", "hello.pyc", "htllo.pyt", "python.exe", "dsadsad.pycds"])
list(p)
files = find(".")
pyfiles = grep(".*\.py$", files)
lines = readlines(pyfiles)
funcs = grep("def ", lines)
count(funcs)
files = find(".")
pyfiles = grep(".*\.py$", files)
lines = readlines(pyfiles)
funcs = grep("def ", lines)
funcs
next(funcs)
import os
def find(path):
for dirpath, dirname, files in os.walk(path):
for f in files:
print("yielding from find")
yield os.path.join(dirpath, f)
def take(seq, n):
return [next(seq) for i in range(n)]
import re
def grep(pattern, seq):
p = re.compile(pattern)
for item in seq:
if p.match(item):
print("yielding from grep")
yield item
def readlines(files):
for f in files:
with open(f) as fd:
for line in fd:
print("yielding from readlines")
yield line
files = find(os.getcwd())
pyfiles = grep(".*\.py$", files)
lines = readlines(pyfiles)
funcs = grep("def ", lines)
next(funcs)
next(funcs)
def createHugeFile(filename):
with open(filename, "w") as f:
for i in range(100000000):
f.write("Some junk statement!\n")
import os
def find(path):
for dirpath, dirname, files in os.walk(path):
for f in files:
yield os.path.join(dirpath, f)
def take(seq, n):
return [next(seq) for i in range(n)]
import re
def grep(pattern, seq):
p = re.compile(pattern)
for item in seq:
if p.match(item):
yield item
def readlines(files):
for f in files:
with open(f) as fd:
for line in fd:
yield line
createHugeFile("/tmp/data.txt")
lines = readlines(["/tmp/data.txt"])
hello = grep("hello python", lines)
next(hello)
problem
get_paragraphs to split given text into paragraphs. The function should take a sequence of lines as argument and returns a sequence of paragraphs. Whenever you encounter an empty line that is end of previous paragraph. https://ia801405.us.archive.org/12/items/prideandprejudic01342gut/pandp12.txtdef get_paragraphs(lines):
para = []
for line in lines:
if line.strip()=="":
if para:
yield "".join(para)
para = []
else:
para.append(line)
if para:
yield "".join(para)
count(get_paragraphs(["A\n","B\n","\n","A\n","\n","\n","A\n"]))
count(get_paragraphs(readlines(["pandp12.txt"])))
%%file paragraph.py
import requests
def download(url, filename):
r = requests.get(url)
with open(filename, "w") as f:
f.write(r.text)
def count(seq):
return sum(1 for i in seq)
def get_paragraphs(lines):
para = []
for line in lines:
if line.strip()=="":
if para:
yield "".join(para)
para = []
else:
para.append(line)
if para:
yield "".join(para)
if __name__ == "__main__":
url = "https://ia801405.us.archive.org/12/items/prideandprejudic01342gut/pandp12.txt"
filename = "pnp.txt"
#download(url, filename)
with open(filename) as lines:
print(count(get_paragraphs(lines)))
!python paragraph.py
%%file test_para.py
import paragraph
def square(x):
return x*x
def test_square():
assert square(-1) == 1
assert square(2) == 4
!pytest -v test_para.py
%%file test_para.py
import paragraph
def square(x):
return x*x
def test_square():
assert square(-1) == 1
assert square(2) == 4
square("s")
!pytest -v test_para.py
%%file test_para.py
import paragraph
import pytest
def square(x):
return x*x
def test_square():
assert square(-1) == 1
assert square(2) == 4
with pytest.raises (TypeError):
square("s")
with pytest.raises (NameError):
square("s")
!pytest -v test_para.py
%%file test_para.py
import pytest
from paragraph import count, get_paragraphs
def test_count():
assert count([]) == 0
assert count((i for i in range(100))) == 100
s = (i for i in range(5))
assert count(s) == 5
assert count(s) == 0
def test_para():
p = get_paragraphs([])
assert count(p) == 0
assert count(get_paragraphs(["\n"])) == 0
assert count(get_paragraphs(["A\n"])) == 1
assert count(get_paragraphs(["A\n","B\n"])) == 1
assert count(get_paragraphs(["A\n","\n"])) == 1
assert count(get_paragraphs(["A\n","\n","\n","A\n" ]))== 2
assert count(get_paragraphs(["A"])) == 1
!pytest -v test_para.py
%%file weekday.py
import datetime
def now():
return datetime.datetime.now()
def weekday():
today = now()
return today.strftime("%A")
import weekday
weekday.weekday()
%%file weekday.py
import datetime
def now():
return datetime.datetime.now()
def weekday():
today = now()
return today.strftime("%A")
%%file test_weekday.py
import weekday
import datetime
def test_weekday(monkeypatch):
today = (2018, 1, 1)
def fakenow():
return datetime.datetime(*today)
monkeypatch.setattr(weekday, "now", fakenow)
assert weekday.weekday() == "Monday"
!pytest -v test_weekday.py
%%file fixture.py
import os
import pytest
def createfile(path_):
with open(path_, "w") as f:
f.write("one")
@pytest.fixture
def path():
path_ = os.path.join(os.getcwd(),"testdir")
if not os.path.exists(path_):
os.mkdir(path_)
yield path_
os.removedirs(path_)
def test_createfile(path):
path_ = os.path.join(path, "test.txt")
createfile(path_)
assert os.path.exists(path_)==True
os.remove(path_)
!pytest -v fixture.py
%%file mymodule.py
print(__name__)
!python mymodule.py
import mymodule