Skip to content
Advertisement

Tag: error-handling

Hide traceback unless a debug flag is set

What is the idiomatic python way to hide traceback errors unless a verbose or debug flag is set? Example code: Existing output now, but only desired when called with foo.py –debug: Desired normal output: Here’s a test script: https://gist.github.com/maphew/e3a75c147cca98019cd8 Answer The short way is using the sys module and use this command: Use your flag to determine the behaviour. Example:

How to return 0 with divide by zero

I’m trying to perform an element wise divide in python, but if a zero is encountered, I need the quotient to just be zero. For example: I could always just use a for-loop through my data, but to really utilize numpy’s optimizations, I need the divide function to return 0 upon divide by zero errors instead of ignoring the error.

How to throw error and exit with a custom message in python

I’ve seen people suggesting sys.exit() in Python. My question is that, is there any other way to exit the execution of current script, I mean termination, with an error. Something like this: Currently my solution would be: Answer Calling sys.exit with a string will work. The docs mention this use explicitly: In particular, sys.exit(“some error message”) is a quick way

Handling a timeout error in Python sockets

I am trying to figure out how to use the try and except to handle a socket timeout. The way I added the socket module was to import everything, but how do I handle exceptions? In the documentation it says you can use socket.timeouterror, but that doesn’t work for me. Also, how would I write the try exception block if

In Python try until no error

I have a piece of code in Python that seems to cause an error probabilistically because it is accessing a server and sometimes that server has a 500 internal server error. I want to keep trying until I do not get the error. My solution was: This seems like a hack to me. Is there a more Pythonic way to

How to check that a regular expression has matched a string completely, i.e. – the string did not contain any extra character?

I have two questions: 1) I have a regular expression ([A-Z][a-z]{0,2})(d*) and I am using Python’s re.finditer() to match appropriate strings. My problem is, that I want to match only strings that contain no extra characters, otherwise I want to raise an exception. I want to catch a following pattern: – capital letter, followed by 0, 1 or 2 small

Advertisement