简体   繁体   中英

How to catch specified error “[Errno 28] No space left on device” in Python

Here is a small part of my Python code:

except Exception1:
    logger.error("Exception 1. Exit.")
    sys.exit(-1)
except Exception 2, e:
    logger.error("Exception 2: {e}".format(e=e.message))

Sometimes I get an error:

INFO - 2019-01-28 16:44:49,399 - data_loader - ERROR - Exception 2: [Errno 28] No space left on device

The problem is that program returns 0 code and I cannot see there was an error.

I found two solutions.

1:

except Exception1:
    logger.error("Exception 1. Exit.")
    sys.exit(-1)
except Exception 2, e:
    logger.error("Exception 2: {e}".format(e=e.message))
    raise

2:

except Exception1:
    logger.error("Exception 1. Exit.")
    sys.exit(-1)
except Exception 2, e:
    logger.error("Exception 2: {e}".format(e=e.message))
except [ExceptionCode]:
    raise("No space left on device")

My question is - how I can catch "no space left on device" in Pyhton? Is there any error code which I can use?

import errno

try:
    ...
except Exception as e:
    if e.errno == errno.ENOSPC:
        # no space left
        # handle it here

If it is a valid exception then you get the name of exception like below. Once you have the name then you can handle that exception gracefully

try:
    #do something
except Exception as exception:
    print(exception.__class__.__name__)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM