usage of try except for review.
Ganesh Pal
ganesh1pal at gmail.com
Mon Feb 29 03:13:29 EST 2016
Iam on python 2.6 and Linux , need your suggestion on the usage of try
and except in this program and
Modified code:
#!/usr/bin/env python
"""
"""
import os
import shlex
import subprocess
import sys
import time
import logging
import run
import pdb
def run_cmd_and_verify(cmd, timeout=1000):
try:
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \
" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
logging.error("Failed to run %s got %s" % (cmd, e))
return False
return True
def run_test():
"""
Mount
"""
pdb.set_trace()
for cmd in ["mount /nfs_mount1", "mount /cifs_mount1"]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
logging.error("Failure while running command %")
logging.info("Setup and Creation ....Done !!!")
#
cmd = "run_scan"
out, err, ret = run(cmd)
for cmd in ["create_data.py -nfs ",
"validate.py -30 "]:
try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
logging.error("")
return False
logging.info("Mount IS START.....Done !!!")
def main():
if not run_test():
sys.exit("Exiting Main")
if __name__ == '__main__':
main()
Question 1:
1. Have I used try and expect block correctly ? , In my case I have
the except block that's is not needed it just gives an message I
have still included for the sake of try block
try:
if not run_cmd_and_verify(cmd, timeout=3600):
return False
except:
logging.error("inside except")
return False
2. If a failure’s are encountered the error by assert condition the
errors are now displayed on the screen , how do I redirect it to log
file using logging error
def run_cmd_and_verify(cmd, timeout=1000):
try:
out, err, ret = run(cmd, timeout=timeout)
assert ret ==0,"ERROR (ret %d): " \
" \nout: %s\nerr: %s\n" % (ret, out, err)
except Exception as e:
logging.error("Failed to run %s got %s" % (cmd, e))
return False
return True
#script_10.py
Failed to run mount /nfs got ERROR (ret 1):
out:
host-44-3 exited with status 1
err:
host-44-3: mount_efs: on /nfs: efs is already mounted
3. my function def has 1000 but Iam using 3600 in the calling fnx etc
, Time out value are overwritten ?
4. Any further improvement particularly on try -except ?
Regards,
Ganesh
More information about the Python-list
mailing list