sys.exit(1) vs raise SystemExit vs raise

Ganesh Pal ganesh1pal at gmail.com
Tue Apr 12 08:50:54 EDT 2016


I m on python 2.7 and Linux , I have a simple code need suggestion if I
 I could replace sys.exit(1) with raise SystemExit .
==Actual code==
def main():
 try:
 create_logdir()
 create_dataset()
 unittest.main()
 except Exception as e:
 logging.exception(e)
 sys.exit(EXIT_STATUS_ERROR)
if __name__ == '__main__':
 main()
==Changed Code==
def main():
 try:
 create_logdir()
 create_dataset()
 unittest.main()
 except Exception as e:
 logging.exception(e)
 raise SystemExit
if __name__ == '__main__':
 main()
2. All the functions in try block have exception bubbled out using raise
 Example for create_logdir() here is the function definition
def create_logdir():
 try:
 os.makedirs(LOG_DIR)
 except OSError as e:
 sys.stderr.write("Failed to create log directory...Exiting !!!")
 raise
 print "log file: " + corrupt_log
 return True
def main():
 try:
 create_logdir()
 except Exception as e:
 logging.exception(e)
 raise SystemExit
(a) In case if create_logdir() fails we will get the below error ,is
this fine or do I need to improve this code.
Failed to create log directory...Exiting !!!ERROR:root:[Errno 17] File
exists: '/var/log/dummy'
Traceback (most recent call last):
 File "corrupt_test.py", line 245, in main
 create_logdir()
 File "corrupt_test.py", line 53, in create_logdir
 os.makedirs(LOG_DIR)
 File "/usr/local/lib/python2.7/os.py", line 157, in makedirs
OSError: [Errno 17] File exists: '/var/log/dummy'
3. Can I have just raise , instead of SystemExit or sys.exit(1) . This
looks wrong to me
 def main():
 try:
 create_logdir()
 except Exception as e
 logging.exception(e)
 raise
 Regards,
Ganesh


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /