Context
Context
For example, opening a file, doing few file operations, and closing the file is
manged using Context Manager as shown below.
content = fp.read()
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
...
'''
#!/bin/python3
import sys
import os
import inspect
if __name__ == "__main__":
try:
filename = str(input())
except:
filename = None
try:
input_text = str(input())
except:
input_text = None
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)
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
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.')
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
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()