0% found this document useful (0 votes)
239 views

Context

A Context Manager allows code to be automatically executed upon entering and exiting a context. It can be used to manage resources like opening and closing files. The 'with' statement in Python enables the use of a context manager to handle opening and closing a resource automatically. Context managers can also be implemented as classes with __enter__ and __exit__ methods to manage other resources like database connections.

Uploaded by

roy.scar2196
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
239 views

Context

A Context Manager allows code to be automatically executed upon entering and exiting a context. It can be used to manage resources like opening and closing files. The 'with' statement in Python enables the use of a context manager to handle opening and closing a resource automatically. Context managers can also be implemented as classes with __enter__ and __exit__ methods to manage other resources like database connections.

Uploaded by

roy.scar2196
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

A Context Manager allows a programmer to perform required activities,

automatically, while entering or exiting a Context.

For example, opening a file, doing few file operations, and closing the file is
manged using Context Manager as shown below.

with open('sample.txt', 'w') as fp:

content = fp.read()

The keyword with is used in Python to enable a context manager. It automatically


takes care of closing the file.

Context Manager...
Consider the following example, which tries to establish a connection to a
database, perform few db operations and finally close the connection.
Example 1

import sqlite3
try:
dbConnection = sqlite3.connect('TEST.db')
cursor = dbConnection.cursor()
'''
Few db operations
...
'''
except Exception:
print('No Connection.')
finally:
dbConnection.close()

Context Manager...
Example 2

import sqlite3
class DbConnect(object):
def __init__(self, dbname):
self.dbname = dbname
def __enter__(self):
self.dbConnection = sqlite3.connect(self.dbname)
return self.dbConnection
def __exit__(self, exc_type, exc_val, exc_tb):
self.dbConnection.close()
with DbConnect('TEST.db') as db: #<--
cursor = db.cursor()
'''
Few db operations
...
'''

Q1:Writing text to a file using 'with'


Coding

#!/bin/python3

import sys
import os
import inspect

# Complete the function below.

def writeTo(filename, input_text):


with open (filename, 'w') as file:
file.write(input_text)

if __name__ == "__main__":
try:
filename = str(input())
except:
filename = None

try:
input_text = str(input())
except:
input_text = None

res = writeTo(filename, input_text)

if 'with' in inspect.getsource(writeTo):
print("'with' used in 'writeTo' function definition.")

if os.path.exists(filename):
print('File :',filename, 'is present on system.')
with open(filename) as fp:
content = fp.read()
if content == input_text:
print('File Contents are :', content)

Q2:Archiving a file using 'with'


Coding

from zipfile import ZipFile #<--


import sys
import os
import inspect

# Define 'writeTo' function below, such that


# it writes input_text string to filename.
def writeTo(filename, input_text):
with open (filename, 'w') as file:
file.write(input_text)
# Define the function 'archive' below, such that
# it archives 'filename' into the 'zipfile'
def archive(zfile, filename):
with ZipFile (zfile, 'w') as myzipfile: #<--
myzipfile.write(filename)

if __name__ == "__main__":
try:
filename = str(input())
except:
filename = None

try:
input_text = str(input())
except:
input_text = None

try:
zip_file = str(input())
except:
zip_file = None

res = writeTo(filename, input_text)

if 'with' in inspect.getsource(writeTo):
print("'with' used in 'writeTo' function definition.")

if os.path.exists(filename):
print('File :',filename, 'is present on system.')

res = archive(zip_file, filename)

if 'with' in inspect.getsource(archive):
print("'with' used in 'archive' function definition.")

if os.path.exists(zip_file):
print('ZipFile :',zip_file, 'is present on system.')

Q3:Give a Try - Run a System Command using Popen utility of Subprocess module
#!/bin/python3

import sys
import os
import subprocess
import inspect

# Complete the function below.

def run_process(cmd_args):
with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
as p:
out, err = p.communicate()
return out

if __name__ == "__main__":
f = open(os.environ['OUTPUT_PATH'], 'w')

cmd_args_cnt = 0
cmd_args_cnt = int(input())
cmd_args_i = 0
cmd_args = []
while cmd_args_i < cmd_args_cnt:
try:
cmd_args_item = str(input())
except:
cmd_args_item = None
cmd_args.append(cmd_args_item)
cmd_args_i += 1
res = run_process(cmd_args);
#f.write(res.decode("utf-8") + "\n")

if 'with' in inspect.getsource(run_process):
f.write("'with' used in 'run_process' function definition.\n")

if 'Popen' in inspect.getsource(run_process):
f.write("'Popen' used in 'run_process' function definition.\n")
f.write('Process Output : %s\n' % (res.decode("utf-8")))

f.close()

You might also like