Practical Python Master Class at VMWare - Day 2

Sep 26-28, 2018 Vikrant Patil

These notes are available online at http://notes.pipal.in/2018/vmware-practical-master-sep/

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

Python distribution

We will be using anaconda (python 3) distribution for this training. it can be downloaded from

https://www.anaconda.com/download/

Inheritance

In [1]:
class Point:
    
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
In [2]:
class RedPoint(Point):
    color = "red"
    
In [3]:
r1 = RedPoint(2,3)
r2 = RedPoint(3,4)
In [4]:
r1.color
Out[4]:
'red'
In [6]:
r2.color
Out[6]:
'red'
In [7]:
class ColoredPoint(Point):
    
    def __init__(self, x, y, color):
        super().__init__(x,y)
        self.color = color
In [10]:
c1 = ColoredPoint(0,0, "white")
In [11]:
c1.color
Out[11]:
'white'
In [27]:
class A:
    
    def __init__(self):
        print("A.__init__")
        
class B(A):
    
    def __init__(self):
        super().__init__()
        print("B.__init__")
        
class C(B):
    
    def __init__(self):
        super().__init__()
        print("C.__init__")
        
class D(C,B):
    
    def __init__(self):
        super().__init__()
        print("D.__init__")
        
        
class A1:
    
    def __init__(self):
        print("A1.__init__")
        
class B1(A1):
    
    def __init__(self):
        A1.__init__(self)
        print("B1.__init__")
        
class C1(B1):
    
    def __init__(self):
        B1.__init__(self)
        print("C1.__init__")
        
        
class D1(C1,B1):
        
    def __init__(self):
        C1.__init__(self)
        B1.__init__(self)
        print("D1.__init__")
In [23]:
c = C()
A.__init__
B.__init__
C.__init__
In [24]:
c1 = C1()
A1.__init__
B1.__init__
C1.__init__
In [25]:
d1 = D1()
A1.__init__
B1.__init__
C1.__init__
A1.__init__
B1.__init__
D1.__init__
In [28]:
d = D()
A.__init__
B.__init__
C.__init__
D.__init__
In [30]:
C.mro()
Out[30]:
[__main__.C, __main__.B, __main__.A, object]

Context manager

In [31]:
with open("data.csv") as csv:
    print(csv.read())
A1,A2,A3,A4
B1,B2,B3,B4
C1,C2,C3,C4
D1,D2,D3,D4
In [35]:
csv.read()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-dad0c4a29d29> in <module>()
----> 1 csv.read()

ValueError: I/O operation on closed file.
In [36]:
if True:
    x = 5
else:
    y = 6
In [37]:
x
Out[37]:
5
In [38]:
y
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-38-009520053b00> in <module>()
----> 1 y

NameError: name 'y' is not defined
In [43]:
import time

class Timer:
    
    def __init__(self):
        self.starttime = 0
        self.endtime = 0
        
    def start(self):
        self.starttime = time.time()
        
    def stop(self):
        self.endtime = time.time()
        
    def get_time_taken(self):
        return self.endtime - self.starttime
    
In [44]:
t = Timer()
In [46]:
t.start()
time.sleep(2)
In [47]:
t.stop()
In [48]:
t.get_time_taken()
Out[48]:
3.903286933898926
In [49]:
import time

class Timer:
    
    def __init__(self):
        self.starttime = 0
        self.endtime = 0
        
    def start(self):
        self.starttime = time.time()
        
    def stop(self):
        self.endtime = time.time()
        
    def get_time_taken(self):
        return self.endtime - self.starttime
    
    
    def __enter__(self):
        self.start()
        return self
    
    def __exit__(self, exception_type, exceptioin, traceback):
        self.stop()
        print("Time taken :", self.get_time_taken())
    
In [50]:
with Timer() as t:
    s = 0.0
    for i in range(10000):
        for j in range(1000):
            s += i*j*1.0
    
Time taken : 3.6198573112487793

problem

  • Write a context manager to create a TCP socket which will open a socket at enter. give handle to socket in with block. and close socket at exit of with block.
In [51]:
s = "hello world!"
In [52]:
b = b"hello world!"
In [53]:
b
Out[53]:
b'hello world!'
In [56]:
import socket
class LazyConnection:
    
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.sock = None
        
    def connect(self):
        if not self.sock:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect((self.host, self.port))
    
    def __enter__(self):
        print("Entering .... with block")
        self.connect()
        return self.sock
    
    def __exit__(self, ecptyp, ecpv, tcb):
        print("Exiting with block ...")
        self.sock.close()
        self.sock = None
        
    
In [61]:
with LazyConnection(host="127.0.0.1", port=3456) as sock:
    sock.send(b"hello!")
    reply = sock.recv(10)
    print(reply)
Entering .... with block
b'HELLO!'
Exiting with block ...
In [62]:
%%file socketserver.py
## this is python2.7 code .. you need to port it to python 3
import SocketServer
import socket
import sys

class MyTCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        data = self.request.recv(2048).strip()
        print "%s wrote: " % self.client_address[0]
        print data
        if data=="close":
            self.request.close()
            self.server.shutdown()
        else:
            self.request.send(data.upper())

def start_server():
    HOST, PORT = "127.0.0.1", 3456
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

def send_client_msg():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("127.0.0.1",3456))
    s.send("This is junk data KJHJKASGHD jhG ASDGH AHSGDJASGH DFJKAGH:OP{IO "*10)
    received = s.recv(1024)
    s.close()
    print "Received: " + received

if __name__ == "__main__":
    start_server()
Writing socketserver.py

classmethod

In [63]:
import datetime
In [64]:
datetime.datetime.now()
Out[64]:
datetime.datetime(2018, 9, 27, 11, 18, 28, 39569)
In [65]:
class Mydate(datetime.datetime):
    pass
In [66]:
Mydate.now()
Out[66]:
Mydate(2018, 9, 27, 11, 19, 19, 170302)
In [67]:
class Foo:
    
    def instance():
        return Foo()
    
class Bar(Foo):
    pass
In [68]:
Foo.instance()
Out[68]:
<__main__.Foo at 0x7f28a6688550>
In [69]:
Bar.instance()
Out[69]:
<__main__.Foo at 0x7f28a6e8c898>
In [85]:
class Foo:
    
    @classmethod
    def instance(cls):
        return cls()
    
    def __repr__(self):
        return "{}".format(type(self))
    
class Bar(Foo):
    pass
    
In [87]:
Bar.instance()
Out[87]:
<class '__main__.Bar'>

Exceptions

In [89]:
sum([1,2,3,4,5])
Out[89]:
15
In [90]:
sum(["1",2,3,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-90-21ea973b126c> in <module>()
----> 1 sum(["1",2,3,3])

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [91]:
def incr(x):
    try:
        return x + 1
    except TypeError as t:
        print("Warning:", t)
        return None
    
    
In [95]:
r = incr(3)
r
Out[95]:
4
In [96]:
r = incr("3")
print(r)
Warning: must be str, not int
None
In [98]:
def incr(x, y=3):
    try:
        x = int(x)
    except TypeError as t:
        print("Warning:", t)
        return None 
    else:
        return x + y ## this block gets executed if no exception occurs
    finally:
        pass # cleanup actions gets executed either case
    
        
In [103]:
def incr_(x, y=3):
    try:
        x = int(x)
    except TypeError as t:
        print("Warning:", t)
        return None 
    else:
        return x + y ## this block gets executed if no exception occurs
    finally:
        y = 5 # cleanup actions gets executed either case
        print("finally",y)
In [104]:
incr_(2)
finally 5
Out[104]:
5
In [105]:
def append(x, y=None):
    if not y:
        y = []
    try:
        y.append(x)
    except TypeError as t:
        print("Warning:", t)
        return None 
    else:
        return y ## this block gets executed if no exception occurs
    finally:
        y.append(1) # cleanup actions gets executed either case
        print("finally",y)
In [106]:
append(2)
finally [2, 1]
Out[106]:
[2, 1]
In [109]:
def append(x, y=None):
    if not y:
        y = []
    try:
        y.append(x)
    except TypeError as t:
        print("Warning:", t)
        return None 
    except NameError as n:
        pass
    else:
        return y[:] ## this block gets executed if no exception occurs
    finally:
        y.append(1) # cleanup actions gets executed either case
        print("finally",y)
In [108]:
append(2)
finally [2, 1]
Out[108]:
[2]

testing

In [110]:
%%file csvparser.py

def csvparser(filename):
    with open(filename,"r") as f:
        return [line.strip().split(",") for line in f]
    
def test_parser():
    assert csvparser("data.csv") == [[]]
    
Writing csvparser.py
In [111]:
!pytest -v csvparser.py
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-practical-master-sep, inifile:
collected 1 item                                                                

csvparser.py::test_parser FAILED

=================================== FAILURES ===================================
_________________________________ test_parser __________________________________

    def test_parser():
>       assert csvparser("data.csv") == [[]]
E       AssertionError: assert [['A1', 'A2',..., 'D3', 'D4']] == [[]]
E         At index 0 diff: ['A1', 'A2', 'A3', 'A4'] != []
E         Left contains more items, first extra item: ['B1', 'B2', 'B3', 'B4']
E         Full diff:
E         + [[]]
E         - [['A1', 'A2', 'A3', 'A4'],
E         -  ['B1', 'B2', 'B3', 'B4'],
E         -  ['C1', 'C2', 'C3', 'C4'],...
E         
E         ...Full output truncated (2 lines hidden), use '-vv' to show

csvparser.py:7: AssertionError
=========================== 1 failed in 0.05 seconds ===========================
In [112]:
%%file csvparser1.py

def csvparser(filename):
    with open(filename,"r") as f:
        return [line.strip().split(",") for line in f]
    
def test_parser():
    assert csvparser("data.csv") == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', 'B2', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', 'D3', 'D4']]
                                    
    
Writing csvparser1.py
In [113]:
!pytest -v csvparser1.py
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-practical-master-sep, inifile:
collected 1 item                                                                

csvparser1.py::test_parser PASSED

=========================== 1 passed in 0.01 seconds ===========================
In [124]:
%%file functions.py
"""
This module for testing docstrings!
"""
def square(x):
    """
    This is a function to compute square!
    >>> square(2)
    4
    >>> square(-1)
    1
    """
    return x*x
Overwriting functions.py
In [125]:
!python -m doctest -v functions.py
Trying:
    square(2)
Expecting:
    4
ok
Trying:
    square(-1)
Expecting:
    1
ok
1 items had no tests:
    functions
1 items passed all tests:
   2 tests in functions.square
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
In [126]:
!pydoc functions
Help on module functions:

NNAAMMEE
    functions - This module for testing docstrings!

FFUUNNCCTTIIOONNSS
    ssqquuaarree(x)
        This is a function to compute square!
        >>> square(2)
        4
        >>> square(-1)
        1

FFIILLEE
    /home/vikrant/trainings/2018/vmware-practical-master-sep/functions.py


In [143]:
%%file csvparser2.py
import pytest

def csvparser(filename):
    with open(filename,"r") as f:
        return [line.strip().split(",") for line in f]

def numeric_csvparser(filename):
    with open(filename,"r") as f:
        data = [line.strip().split(",") for line in f]
        return [[float(s) for s in row] for row in data]
    
def test_parser():
    assert csvparser("data.csv") == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', 'B2', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', 'D3', 'D4']]
    assert csvparser("data1.csv") == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', '', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', '', 'D4']]
    with pytest.raises(ValueError):
        numeric_csvparser("data2.csv")
    
Overwriting csvparser2.py
In [144]:
!cat data.csv
A1,A2,A3,A4
B1,B2,B3,B4
C1,C2,C3,C4
D1,D2,D3,D4
In [145]:
%%file data1.csv
A1,A2,A3,A4
B1,,B3,B4
C1,C2,C3,C4
D1,D2,,D4
Overwriting data1.csv
In [146]:
%%file data2.csv
1,2,3,4
1,1,,1
,2,2,2
3,3,3,3
Overwriting data2.csv
In [147]:
!pytest -v csvparser2.py
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-practical-master-sep, inifile:
collected 1 item                                                                

csvparser2.py::test_parser PASSED

=========================== 1 passed in 0.01 seconds ===========================
In [156]:
%%file csvparser3.py
import pytest

def csvparser(filename):
    with open(filename,"r") as f:
        return [line.strip().split(",") for line in f]

def numeric_csvparser(filename):
    with open(filename,"r") as f:
        data = [line.strip().split(",") for line in f]
        return [[float(s) for s in row] for row in data]
    
    
def float_(x, value=0):
    try:
        return float(x)
    except ValueError as v:
        print("Detected unusual float!")
        return 0
    
def numeric_csvparser_(filename):
    with open(filename,"r") as f:
        data = [line.strip().split(",") for line in f]
        return [[float_(s) for s in row] for row in data]
    
    
def test_parser():
    assert csvparser("data.csv") == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', 'B2', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', 'D3', 'D4']]
    assert csvparser("data1.csv") == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', '', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', '', 'D4']]
    
def test_numeric_parser():
    with pytest.raises(ValueError):
        numeric_csvparser("data2.csv")
        
def test_parser_missing_values():
    assert numeric_csvparser_("data2.csv") == [[1,2,3,4],[1,1,0,1],[0,2,2,2],[3,3,3,3]]
Overwriting csvparser3.py
In [151]:
def numeric_csvparser(filename):
    with open(filename,"r") as f:
        data = [line.strip().split(",") for line in f]
        return [[float(s) for s in row] for row in data]
In [152]:
numeric_csvparser("data2.csv")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-152-c383bb210c87> in <module>()
----> 1 numeric_csvparser("data2.csv")

<ipython-input-151-0df22c81d1f9> in numeric_csvparser(filename)
      2     with open(filename,"r") as f:
      3         data = [line.strip().split(",") for line in f]
----> 4         return [[float(s) for s in row] for row in data]

<ipython-input-151-0df22c81d1f9> in <listcomp>(.0)
      2     with open(filename,"r") as f:
      3         data = [line.strip().split(",") for line in f]
----> 4         return [[float(s) for s in row] for row in data]

<ipython-input-151-0df22c81d1f9> in <listcomp>(.0)
      2     with open(filename,"r") as f:
      3         data = [line.strip().split(",") for line in f]
----> 4         return [[float(s) for s in row] for row in data]

ValueError: could not convert string to float: 
In [155]:
!pytest -v csvparser3.py
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-practical-master-sep, inifile:
collected 1 item                                                                

csvparser3.py::test_parser PASSED

=========================== 1 passed in 0.01 seconds ===========================
In [162]:
def hello():
    msg = yield "hello! how are you?"
    yield "What the hell do you mean? " + msg
In [163]:
h = hello()
In [164]:
h
Out[164]:
<generator object hello at 0x7f28a6a423b8>
In [165]:
next(h)
Out[165]:
'hello! how are you?'
In [166]:
h.send("hello, I am fine!")
Out[166]:
'What the hell do you mean? hello, I am fine!'
In [167]:
next(h)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-167-6b3a88493d78> in <module>()
----> 1 next(h)

StopIteration: 
In [168]:
h = hello()
In [169]:
h.send("hello, how are you?")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-169-7f0ebbe467c4> in <module>()
----> 1 h.send("hello, how are you?")

TypeError: can't send non-None value to a just-started generator
In [170]:
h.send(None)
Out[170]:
'hello! how are you?'
In [171]:
next(h)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-171-6b3a88493d78> in <module>()
----> 1 next(h)

<ipython-input-162-9d63781a8746> in hello()
      1 def hello():
      2     msg = yield "hello! how are you?"
----> 3     yield "What the hell do you mean? " + msg

TypeError: must be str, not NoneType
In [172]:
h.send("hello, I am fine!")
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-172-59b245b5c00a> in <module>()
----> 1 h.send("hello, I am fine!")

StopIteration: 
In [183]:
%%file csvparser4.py
import pytest
import tempfile


def csvparser(filename):
    with open(filename,"r") as f:
        return [line.strip().split(",") for line in f]

def numeric_csvparser(filename):
    with open(filename,"r") as f:
        data = [line.strip().split(",") for line in f]
        return [[float(s) for s in row] for row in data]
    
    
def float_(x, value=0):
    try:
        return float(x)
    except ValueError as v:
        print("Detected unusual float!")
        return 0
    
def numeric_csvparser_(filename):
    with open(filename,"r") as f:
        data = [line.strip().split(",") for line in f]
        return [[float_(s) for s in row] for row in data]
    

@pytest.fixture
def data():
    x,filename = tempfile.mkstemp("csv")
    with open(filename, "w") as f:
        f.write('A1,A2,A3,A4\nB1,B2,B3,B4\nC1,C2,C3,C4\nD1,D2,D3,D4')

    yield filename
    

@pytest.fixture
def data1():
    x,filename = tempfile.mkstemp("csv")
    with open(filename, "w") as f:
        f.write('A1,A2,A3,A4\nB1,,B3,B4\nC1,C2,C3,C4\nD1,D2,,D4')

    yield filename
    
@pytest.fixture
def data2():
    x,filename = tempfile.mkstemp("csv")
    with open(filename, "w") as f:
        f.write('1,2,3,4\n1,1,,1\n,2,2,2\n3,3,3,3')
    yield filename
    
    
def test_parser(data, data1):
    assert csvparser(data) == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', 'B2', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', 'D3', 'D4']]
    
    assert csvparser(data1) == [['A1', 'A2', 'A3', 'A4'],
                                     ['B1', '', 'B3', 'B4'],
                                     ['C1', 'C2', 'C3', 'C4'],
                                     ['D1', 'D2', '', 'D4']]
    
    
def test_numeric_parser(data2):
    with pytest.raises(ValueError):
        numeric_csvparser(data2)
        
def test_parser_missing_values(data2):
    assert numeric_csvparser_(data2) == [[1,2,3,4],[1,1,0,1],[0,2,2,2],[3,3,3,3]]
Overwriting csvparser4.py
In [173]:
import tempfile
In [174]:
 tempfile.mkstemp("csv")
Out[174]:
(66, '/tmp/tmpo69ao69bcsv')
In [177]:
open("data2.csv").read()
Out[177]:
'1,2,3,4\n1,1,,1\n,2,2,2\n3,3,3,3'
In [182]:
!pytest -v csvparser4.py
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-practical-master-sep, inifile:
collected 3 items                                                               

csvparser4.py::test_parser PASSED
csvparser4.py::test_numeric_parser PASSED
csvparser4.py::test_parser_missing_values PASSED

=========================== 3 passed in 0.02 seconds ===========================

Monkeypacthing

In [206]:
%%file weekday.py
import datetime

def now():
    return datetime.datetime.now()

def weekday():
    n = now()
    return n.strftime("%A")
Overwriting weekday.py
In [189]:
import weekday
In [190]:
weekday.weekday()
Out[190]:
'Thursday'
In [214]:
%%file test_weekday.py

import weekday
import datetime

def test_weekday(monkeypatch):
    
    def fakenow():
        return datetime.datetime(*today)

    monkeypatch.setattr(weekday, "now", fakenow)
    
    today = (2018, 1, 1)
    assert weekday.weekday() == "Monday"
    today = (2018, 1, 2)
    assert weekday.weekday() == "Tuesday"
    
Overwriting test_weekday.py
In [215]:
def add(x,y):
    return x+y
In [216]:
add(2,3)
Out[216]:
5
In [217]:
params = (3,4)
In [218]:
add(params)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-218-b05b7ab7eee0> in <module>()
----> 1 add(params)

TypeError: add() missing 1 required positional argument: 'y'
In [219]:
add(*params)
Out[219]:
7
In [220]:
!pytest -v test_weekday.py
============================= test session starts ==============================
platform linux -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 -- /home/vikrant/usr/local/anaconda3/bin/python
cachedir: .cache
rootdir: /home/vikrant/trainings/2018/vmware-practical-master-sep, inifile:
collected 1 item                                                                

test_weekday.py::test_weekday PASSED

=========================== 1 passed in 0.01 seconds ===========================

profiling

In [231]:
import cProfile
import time

def square(x):
    time.sleep(1)
    return x*x
    
def SSQ(numbers):
    ssq = sum(square(i) for i in numbers)
    s = sum(numbers)
    e = sum(i for i in numbers if i%2==0)
    return ssq + s +e
In [227]:
%%file ssq.py
import time

def square(x):
    time.sleep(1)
    return x*x
    
def SSQ(numbers):
    ssq = sum(square(i) for i in numbers)
    s = sum(numbers)
    e = sum(i for i in numbers if i%2==0)
    return ssq + s +e

if __name__ == "__main__":
    SSQ(range(10))
Writing ssq.py
In [223]:
SSQ(range(10))
Out[223]:
350
In [230]:
cProfile.run("SSQ(range(10))")
         44 function calls in 10.013 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        6    0.000    0.000    0.000    0.000 <ipython-input-222-bf4232e1833c>:10(<genexpr>)
       10    0.000    0.000   10.012    1.001 <ipython-input-222-bf4232e1833c>:3(square)
        1    0.000    0.000   10.013   10.013 <ipython-input-222-bf4232e1833c>:7(SSQ)
       11    0.000    0.000   10.012    0.910 <ipython-input-222-bf4232e1833c>:8(<genexpr>)
        1    0.000    0.000   10.013   10.013 <string>:1(<module>)
        1    0.000    0.000   10.013   10.013 {built-in method builtins.exec}
        3    0.000    0.000   10.012    3.337 {built-in method builtins.sum}
       10   10.012    1.001   10.012    1.001 {built-in method time.sleep}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


In [229]:
!python -m cProfile -s cumtime ssq.py
         44 function calls in 10.012 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   10.012   10.012 {built-in method builtins.exec}
        1    0.000    0.000   10.012   10.012 ssq.py:1(<module>)
        1    0.000    0.000   10.012   10.012 ssq.py:7(SSQ)
        3    0.000    0.000   10.012    3.337 {built-in method builtins.sum}
       11    0.000    0.000   10.012    0.910 ssq.py:8(<genexpr>)
       10    0.000    0.000   10.012    1.001 ssq.py:3(square)
       10   10.012    1.001   10.012    1.001 {built-in method time.sleep}
        6    0.000    0.000    0.000    0.000 ssq.py:10(<genexpr>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


In [249]:
import math
def fun(n):
    s = 0
    for i in range(n):
        s += math.sqrt(i)   ##math.sqrt has repeted hidden call for checking attribute and then accesing it!
    return s

def morefun(n):
    s = 0
    sqrt = math.sqrt ### locals are faster than global variables
    for i in range(n):
        s += sqrt(i)
    return s
In [246]:
n = 100000000
In [247]:
with Timer() as t:
    fun(n)
Time taken : 23.342923879623413
In [248]:
with Timer() as t:
    morefun(n)
Time taken : 15.961802959442139

debugging

python comes with gdb like debugger pdb. it works just like gdb, you can put break points, execute till break point, examine data, continue to next break point. delete /disable and add new breakpoints.

Working with files and folders

In [250]:
import os
In [251]:
os.getcwd()  ### current working directory
Out[251]:
'/home/vikrant/trainings/2018/vmware-practical-master-sep'
In [253]:
os.listdir(".") ## returns list of all files and folders from given directory
Out[253]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'data2.csv',
 'data1.csv',
 'socketserver.py',
 'csvparser.py',
 'csvparser2.py',
 'bank1.py',
 'test_weekday.py',
 'day2.ipynb',
 'day2.html',
 'ssq.py',
 '.cache',
 'csvparser4.py',
 'day3.ipynb',
 'functions.py',
 'data.csv',
 'csvparser1.py',
 'outline.html',
 'weekday.py',
 'day3.html',
 'Makefile',
 'csvparser3.py',
 '__pycache__',
 'day1.html',
 'bank0.py']
In [255]:
len(os.listdir("."))
Out[255]:
27
In [256]:
os.path.exists("./hello.py")
Out[256]:
False
In [258]:
os.path.exists("day1.html")
Out[258]:
True
In [260]:
os.path.join(os.getcwd(), "output.txt")
Out[260]:
'/home/vikrant/trainings/2018/vmware-practical-master-sep/output.txt'
In [261]:
os.path.isfile("day1.html")
Out[261]:
True

problem

  • write a function to print directory tree.
In [263]:
!tree ~/trainings/2018/
/home/vikrant/trainings/2018/
├── mit-pune-march
│   ├── bank0.py
│   ├── bank1.py
│   ├── cat.py
│   ├── data_science.html
│   ├── data_science.ipynb
│   ├── data.txt
│   ├── day1.html
│   ├── day1.ipynb
│   ├── day2.html
│   ├── day2.ipynb
│   ├── day3.html
│   ├── day3.ipynb
│   ├── echo.py
│   ├── grep.py
│   ├── head.py
│   ├── Heart_Disease_Data.csv
│   ├── Heart_Disease_Not-Processed.csv
│   ├── hello1.py
│   ├── hello.py
│   ├── ls.py
│   ├── main.py
│   ├── Makefile
│   ├── module1.py
│   ├── module2.py
│   ├── module.py
│   ├── numbers.txt
│   ├── push
│   ├── __pycache__
│   │   ├── bank0.cpython-36.pyc
│   │   └── bank1.cpython-36.pyc
│   ├── regional.txt
│   ├── square1.py
│   ├── square.py
│   ├── tables1.csv
│   ├── tables1.csv~
│   ├── tables.csv
│   ├── Untitled.html
│   ├── wc.py
│   ├── words.txt
│   └── x.txt
├── vmware-advanced-apr
│   ├── bank0.py
│   ├── bank1.py
│   ├── cat.py
│   ├── commands.py
│   ├── data.csv
│   ├── day1.html
│   ├── day1.ipynb
│   ├── day2.html
│   ├── day2.ipynb
│   ├── day3.html
│   ├── day3.ipynb
│   ├── fib1.py
│   ├── fib.py
│   ├── functions1.py
│   ├── functions.py
│   ├── functionstest.py
│   ├── grub.conf
│   ├── Makefile
│   ├── memoize.py
│   ├── mytcpserver.py
│   ├── notebooks
│   │   ├── day1.ipynb
│   │   ├── day2.ipynb
│   │   └── day3.ipynb
│   ├── notebooks.zip
│   ├── pcpu.py
│   ├── pnp.txt
│   ├── push
│   ├── __pycache__
│   │   ├── commands.cpython-36.pyc
│   │   ├── functionstest.cpython-36-PYTEST.pyc
│   │   ├── memoize.cpython-36.pyc
│   │   ├── setupteardown.cpython-36-PYTEST.pyc
│   │   ├── test_weekday.cpython-36-PYTEST.pyc
│   │   ├── trace.cpython-36.pyc
│   │   └── weekday.cpython-36.pyc
│   ├── setupteardown.py
│   ├── sockets.py
│   ├── sockets.py~
│   ├── tcpu.py
│   ├── tdownload.py
│   ├── test_weekday.py
│   ├── thread.py
│   ├── tpdownload.py
│   ├── trace.py
│   ├── trace.py~
│   └── weekday.py
├── vmware-advanced-may
│   ├── 0.txt
│   ├── 1.txt
│   ├── 2.txt
│   ├── 3.txt
│   ├── bank0.py
│   ├── bank1.py
│   ├── commands.py
│   ├── day1.html
│   ├── day1.ipynb
│   ├── day2.html
│   ├── day2.ipynb
│   ├── day3.html
│   ├── day3.ipynb
│   ├── fib1.py
│   ├── fib.py
│   ├── fixture.py
│   ├── functions.py
│   ├── grep.py
│   ├── Makefile
│   ├── memoize.py
│   ├── mymodule.py
│   ├── numbers.txt
│   ├── pandp12.txt
│   ├── paragraph.py
│   ├── pcpu.py
│   ├── pnp.txt
│   ├── push
│   ├── __pycache__
│   │   ├── bank0.cpython-36.pyc
│   │   ├── commands.cpython-36.pyc
│   │   ├── fixture.cpython-36-PYTEST.pyc
│   │   ├── memoize.cpython-36.pyc
│   │   ├── mymodule.cpython-36.pyc
│   │   ├── paragraph.cpython-36.pyc
│   │   ├── test_para.cpython-36-PYTEST.pyc
│   │   ├── test_weekday.cpython-36-PYTEST.pyc
│   │   ├── trace.cpython-36.pyc
│   │   └── weekday.cpython-36.pyc
│   ├── sockets.py
│   ├── tables.csv
│   ├── tdownload.py
│   ├── test_para.py
│   ├── test_weekday.py
│   ├── Thread-1.txt
│   ├── Thread-2.txt
│   ├── Thread-3.txt
│   ├── Thread-4.txt
│   ├── tpdownload.py
│   ├── trace.py
│   └── weekday.py
├── vmware-feb-python
│   ├── add1.py
│   ├── add2.py
│   ├── add.py
│   ├── anagrams.txt
│   ├── bank0.py
│   ├── bank1.py
│   ├── binary.bin
│   ├── cat.py
│   ├── data.csv
│   ├── data.txt
│   ├── day1.html
│   ├── day1.ipynb
│   ├── day2.html
│   ├── day2.ipynb
│   ├── day3.html
│   ├── day3.ipynb
│   ├── functions.py
│   ├── grep.py
│   ├── head.py
│   ├── light.py
│   ├── ls.py
│   ├── Makefile
│   ├── module1.py
│   ├── module.py
│   ├── notebooks
│   │   ├── day1.ipynb
│   │   ├── day2.ipynb
│   │   └── day3.ipynb
│   ├── notebooks.zip
│   ├── numbers.txt
│   ├── push
│   ├── __pycache__
│   │   ├── add1.cpython-36.pyc
│   │   ├── add2.cpython-36.pyc
│   │   ├── add.cpython-36.pyc
│   │   ├── functions.cpython-36.pyc
│   │   ├── functions.cpython-36-PYTEST.pyc
│   │   ├── light.cpython-36.pyc
│   │   ├── module.cpython-36.pyc
│   │   └── wc.cpython-36.pyc
│   ├── tables.csv
│   ├── tables.csv~
│   ├── test.txt
│   ├── wc.py
│   └── words.txt
├── vmware-jan-python
│   ├── add.p
│   ├── add.py
│   ├── args.py
│   ├── bank0.py
│   ├── bank1.py
│   ├── bank2.py
│   ├── binary.bin
│   ├── cat.py
│   ├── data.txt
│   ├── day1.html
│   ├── day1.ipynb
│   ├── day2.html
│   ├── day2.ipynb
│   ├── day3.html
│   ├── day3.ipynb
│   ├── echo.py
│   ├── functions.py
│   ├── grub.cnf
│   ├── head.py
│   ├── hello1.py
│   ├── hello.py
│   ├── links.txt
│   ├── links.txt~
│   ├── ls.py
│   ├── Makefile
│   ├── moddule1.py
│   ├── module1.py
│   ├── module2.py
│   ├── m.py
│   ├── mymodule.py
│   ├── myscript.py
│   ├── numbers.txt
│   ├── nums.csv
│   ├── push
│   ├── __pycache__
│   │   ├── functions.cpython-36.pyc
│   │   ├── functions.cpython-36-PYTEST.pyc
│   │   ├── hello1.cpython-36.pyc
│   │   ├── hello.cpython-36.pyc
│   │   ├── m.cpython-36.pyc
│   │   ├── module1.cpython-36.pyc
│   │   ├── module2.cpython-36.pyc
│   │   ├── mymodule.cpython-36.pyc
│   │   ├── wc.cpython-36.pyc
│   │   └── wordfreq.cpython-36.pyc
│   ├── regional.txt
│   ├── tables.csv
│   ├── tables.tsv
│   ├── unix command head approximately
│   ├── Untitled.html
│   ├── wc.py
│   ├── wordfreq.py
│   └── words.txt
├── vmware-practical-master-sep
│   ├── bank0.py
│   ├── bank1.py
│   ├── csvparser1.py
│   ├── csvparser2.py
│   ├── csvparser3.py
│   ├── csvparser4.py
│   ├── csvparser.py
│   ├── data1.csv
│   ├── data2.csv
│   ├── data.csv
│   ├── day1.html
│   ├── day1.ipynb
│   ├── day2.html
│   ├── day2.ipynb
│   ├── day3.html
│   ├── day3.ipynb
│   ├── functions.py
│   ├── Makefile
│   ├── outline.html
│   ├── push
│   ├── __pycache__
│   │   ├── bank0.cpython-36.pyc
│   │   ├── bank1.cpython-36.pyc
│   │   ├── csvparser1.cpython-36-PYTEST.pyc
│   │   ├── csvparser2.cpython-36-PYTEST.pyc
│   │   ├── csvparser3.cpython-36-PYTEST.pyc
│   │   ├── csvparser4.cpython-36-PYTEST.pyc
│   │   ├── csvparser.cpython-36-PYTEST.pyc
│   │   ├── functions.cpython-36.pyc
│   │   ├── test_weekday.cpython-36-PYTEST.pyc
│   │   └── weekday.cpython-36.pyc
│   ├── socketserver.py
│   ├── ssq.py
│   ├── test_weekday.py
│   └── weekday.py
└── vmware-pune-jan-python
    ├── bank0.py
    ├── bank1.py
    ├── bank2.py
    ├── binary.bin
    ├── cat.py
    ├── data.txt
    ├── day1.html
    ├── day1.ipynb
    ├── day2.html
    ├── day2.ipynb
    ├── day3.html
    ├── day3.ipynb
    ├── echo.py
    ├── functions.py
    ├── grep.py
    ├── head.py
    ├── hello1.py
    ├── hello2.py
    ├── hello3.py
    ├── hello.py
    ├── links.txt
    ├── links.txt~
    ├── ls.py
    ├── Makefile
    ├── missing.txt
    ├── module1.py
    ├── mymodule.py
    ├── myscript.py
    ├── mysum.py
    ├── numbers.txt
    ├── primes.txt
    ├── product.py
    ├── push
    ├── __pycache__
    │   ├── functions.cpython-36-PYTEST.pyc
    │   ├── hello1.cpython-36.pyc
    │   ├── hello2.cpython-36.pyc
    │   ├── hello3.cpython-36.pyc
    │   ├── hello.cpython-36.pyc
    │   ├── module1.cpython-36.pyc
    │   ├── mymodule.cpython-36.pyc
    │   ├── product.cpython-36.pyc
    │   ├── product.cpython-36-PYTEST.pyc
    │   ├── square1.cpython-36.pyc
    │   ├── square3.cpython-36.pyc
    │   └── wc.cpython-36.pyc
    ├── regional.txt
    ├── square1.py
    ├── square3.py
    ├── square.py
    ├── tables.csv
    ├── wc.py
    ├── words.txt
    └── yes.py

16 directories, 315 files
In [273]:
def tree(path, level=0):
    print("| "*level + "|--"+ path)
    for item in os.listdir(path):
        p = os.path.join(path, item)
        if os.path.isfile(p):
            print("| "*level + "|--" + item) 
        else:
            tree(p, level+1)
In [274]:
tree(".")
|--.
| |--./.ipynb_checkpoints
| |--day3-checkpoint.ipynb
| |--day1-checkpoint.ipynb
| |--day2-checkpoint.ipynb
|--push
|--day1.ipynb
|--data2.csv
|--data1.csv
|--socketserver.py
|--csvparser.py
|--csvparser2.py
|--bank1.py
|--test_weekday.py
|--day2.ipynb
|--day2.html
|--ssq.py
| |--./.cache
| | |--./.cache/v
| | | |--./.cache/v/cache
| | | |--lastfailed
|--csvparser4.py
|--day3.ipynb
|--functions.py
|--data.csv
|--csvparser1.py
|--outline.html
|--weekday.py
|--day3.html
|--Makefile
|--csvparser3.py
| |--./__pycache__
| |--csvparser2.cpython-36-PYTEST.pyc
| |--bank1.cpython-36.pyc
| |--csvparser3.cpython-36-PYTEST.pyc
| |--weekday.cpython-36.pyc
| |--test_weekday.cpython-36-PYTEST.pyc
| |--csvparser1.cpython-36-PYTEST.pyc
| |--functions.cpython-36.pyc
| |--bank0.cpython-36.pyc
| |--csvparser.cpython-36-PYTEST.pyc
| |--csvparser4.cpython-36-PYTEST.pyc
|--day1.html
|--bank0.py
In [275]:
os.mkdir("test")
In [276]:
os.path.isdir("test")
Out[276]:
True
In [280]:
os.makedirs("test/hello/nested")
In [281]:
os.rmdir("test/hello/nested/")
In [282]:
tree("test/")
|--test/
| |--test/hello
In [283]:
os.chdir("test/")
In [284]:
os.getcwd()
Out[284]:
'/home/vikrant/trainings/2018/vmware-practical-master-sep/test'
In [285]:
os.chdir("../")
In [287]:
for path, dirs, files in os.walk("."):
    for f in files:
        print(os.path.join(path, f))
./push
./day1.ipynb
./data2.csv
./data1.csv
./socketserver.py
./csvparser.py
./csvparser2.py
./bank1.py
./test_weekday.py
./day2.ipynb
./day2.html
./ssq.py
./csvparser4.py
./day3.ipynb
./functions.py
./data.csv
./csvparser1.py
./outline.html
./weekday.py
./day3.html
./Makefile
./csvparser3.py
./day1.html
./bank0.py
./.ipynb_checkpoints/day3-checkpoint.ipynb
./.ipynb_checkpoints/day1-checkpoint.ipynb
./.ipynb_checkpoints/day2-checkpoint.ipynb
./.cache/v/cache/lastfailed
./__pycache__/csvparser2.cpython-36-PYTEST.pyc
./__pycache__/bank1.cpython-36.pyc
./__pycache__/csvparser3.cpython-36-PYTEST.pyc
./__pycache__/weekday.cpython-36.pyc
./__pycache__/test_weekday.cpython-36-PYTEST.pyc
./__pycache__/csvparser1.cpython-36-PYTEST.pyc
./__pycache__/functions.cpython-36.pyc
./__pycache__/bank0.cpython-36.pyc
./__pycache__/csvparser.cpython-36-PYTEST.pyc
./__pycache__/csvparser4.cpython-36-PYTEST.pyc
In [288]:
os.path.basename("/home/vikrant/programming/explorations/python/example.py")
Out[288]:
'example.py'
In [289]:
os.path.dirname("/home/vikrant/programming/explorations/python/example.py")
Out[289]:
'/home/vikrant/programming/explorations/python'

Working with permissions

In [293]:
os.access("test/", os.R_OK) # check read permission
Out[293]:
True
In [294]:
os.access("test/", os.X_OK) # check execute permission
Out[294]:
True
In [297]:
os.access("test/", os.W_OK) #write
Out[297]:
True
In [299]:
import stat
In [300]:
os.chmod("test/" , stat.S_IREAD|stat.S_IWRITE)
In [301]:
!ls -ld test/
drw------- 3 vikrant vikrant 4096 Sep 27 15:56 test/
In [302]:
os.lstat("test/")
Out[302]:
os.stat_result(st_mode=16768, st_ino=4201376, st_dev=2052, st_nlink=3, st_uid=1000, st_gid=1000, st_size=4096, st_atime=1538044062, st_mtime=1538043963, st_ctime=1538044656)
In [303]:
stat.S_IMODE(os.lstat("test/").st_mode)
Out[303]:
384
In [304]:
os.path.getsize("day1.html")
Out[304]:
453583

problem

  • Write a function to compute size of a directory. consider all files recursively from that ditrectory
  • Write a function find which finds all files with extension ".log" from given directory
In [305]:
def dirsize(dirname):
    s = 0
    for path, dirs , files in os.walk(dirname):
        s += sum(os.path.getsize(os.path.join(path, f)) for f in files)
    return s
In [309]:
dirsize(".")/1024/1024
Out[309]:
1.3834972381591797
In [307]:
!du -sh .
du: cannot access './test/hello': Permission denied
1.6M	.
In [310]:
def find(dirpath, ext="log"):
    for path, dirs, files in os.walk(dirpath):
        for f in files:
            if f.endswith("."+ext):
                yield os.path.join(path, f)
In [316]:
def countdown(n):
    print("start")
    while n>0:
        yield n
        print("back")
        n -= 1
    print("end")
In [312]:
for i in countdown(10):
    print(i, end=" ")
10 9 8 7 6 5 4 3 2 1 
In [313]:
def lineemitter(files):
    for file in files:
        with open(file) as f:
            yield f.readline()
In [326]:
logfiles = find("/var/log/")
In [315]:
lines = lineemitter(logfiles)
In [318]:
counter = countdown(5)
In [319]:
next(counter)
start
Out[319]:
5
In [320]:
def grep(seq, pattern):
    for item in seq:
        if pattern in item:
            yield item
In [321]:
searchresult = grep(lines, "X11/75dpi")
In [322]:
next(searchresult)
---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-322-7a0998fa5537> in <module>()
----> 1 next(searchresult)

<ipython-input-320-004c2317c0fe> in grep(seq, pattern)
      1 def grep(seq, pattern):
----> 2     for item in seq:
      3         if pattern in item:
      4             yield item

<ipython-input-313-bbe067affdca> in lineemitter(files)
      1 def lineemitter(files):
      2     for file in files:
----> 3         with open(file) as f:
      4             yield f.readline()

PermissionError: [Errno 13] Permission denied: '/var/log/lightdm/x-0.log'
In [323]:
def take(n, seq):
    return [next(seq) for i in range(n)]
In [324]:
take(5, logfiles)
Out[324]:
['/var/log/lightdm/x-2.log',
 '/var/log/lightdm/seat0-greeter.log',
 '/var/log/lightdm/x-1.log',
 '/var/log/lightdm/lightdm.log',
 '/var/log/installer/casper.log']
In [327]:
for file in logfiles:
    print(file)
/var/log/auth.log
/var/log/gpu-manager.log
/var/log/Xorg.1.log
/var/log/kern.log
/var/log/boot.log
/var/log/alternatives.log
/var/log/Xorg.2.log
/var/log/dpkg.log
/var/log/Xorg.0.log
/var/log/fontconfig.log
/var/log/bootstrap.log
/var/log/mintsystem.log
/var/log/apt/term.log
/var/log/apt/history.log
/var/log/lightdm/x-0.log
/var/log/lightdm/x-2.log
/var/log/lightdm/seat0-greeter.log
/var/log/lightdm/x-1.log
/var/log/lightdm/lightdm.log
/var/log/installer/casper.log
In [328]:
os.path.getmtime(".")
Out[328]:
1538046831.580756
In [329]:
import time
In [330]:
time.ctime(os.path.getmtime("."))
Out[330]:
'Thu Sep 27 16:45:51 2018'

problem

  • Write a function to find files modified within given number of seconds
In [331]:
import time
def modifiedwithin(files, seconds):
    now = time.time()
    for f in files:
        t = os.path.getmtime(f)
        if now - t <= seconds:
            yield f
In [332]:
logfiles = find("/var/log")
latest = modifiedwithin(logfiles, 1000)
In [333]:
list(latest)
Out[333]:
['/var/log/kern.log', '/var/log/Xorg.0.log']

copying and moving files

In [334]:
import shutil
In [336]:
shutil.copy("./test_weekday.py", "/tmp/") #copies files
Out[336]:
'/tmp/test_weekday.py'
In [337]:
os.path.exists("/tmp/test_weekday.py")
Out[337]:
True
In [338]:
shutil.copy2("./test_weekday.py", "/tmp/")# copies files with metadata
Out[338]:
'/tmp/test_weekday.py'
In [340]:
shutil.copytree(".", "/tmp/training")
---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-340-c86cbfdf3b38> in <module>()
----> 1 shutil.copytree(".", "/tmp/training")

~/usr/local/anaconda3/lib/python3.6/shutil.py in copytree(src, dst, symlinks, ignore, copy_function, ignore_dangling_symlinks)
    357             errors.append((src, dst, str(why)))
    358     if errors:
--> 359         raise Error(errors)
    360     return dst
    361 

Error: [('./test/hello', '/tmp/training/test/hello', "[Errno 13] Permission denied: './test/hello'")]
In [342]:
shutil.copytree(".", "/tmp/training1")
Out[342]:
'/tmp/training1'
In [343]:
tree("/tmp/training1/")
|--/tmp/training1/
|--csvparser1.py
|--weekday.py
|--socketserver.py
|--day1.ipynb
|--test_weekday.py
|--Makefile
|--data2.csv
|--csvparser4.py
|--csvparser.py
|--data1.csv
| |--/tmp/training1/.cache
| | |--/tmp/training1/.cache/v
| | | |--/tmp/training1/.cache/v/cache
| | | |--lastfailed
|--functions.py
|--csvparser3.py
|--day1.html
|--push
|--csvparser2.py
|--day3.html
| |--/tmp/training1/__pycache__
| |--csvparser4.cpython-36-PYTEST.pyc
| |--csvparser.cpython-36-PYTEST.pyc
| |--bank1.cpython-36.pyc
| |--csvparser1.cpython-36-PYTEST.pyc
| |--csvparser2.cpython-36-PYTEST.pyc
| |--weekday.cpython-36.pyc
| |--bank0.cpython-36.pyc
| |--test_weekday.cpython-36-PYTEST.pyc
| |--functions.cpython-36.pyc
| |--csvparser3.cpython-36-PYTEST.pyc
|--bank1.py
|--ssq.py
|--day2.html
|--day2.ipynb
| |--/tmp/training1/.ipynb_checkpoints
| |--day2-checkpoint.ipynb
| |--day1-checkpoint.ipynb
| |--day3-checkpoint.ipynb
|--outline.html
|--bank0.py
|--data.csv
|--day3.ipynb
In [344]:
import filecmp
In [345]:
filecmp.cmp("./test_weekday.py", "/tmp/training1/test_weekday.py")
Out[345]:
True

problem

  • Write a script to backup folder. Assume that folder has huge data, so make sure to backup only new or modified files. don't touch already backed up files but not modified. backup function will be used to take system backup at periodic interval.
In [ ]: