This article is the collection of python skills, tricks and intresting code about python.
1. What's the different of repr(e) and str(e) in exception handling?
let's go straight to the code
def test():
try:
a = 10 / 0
except ZeroDivisionError as ex:
print(f'''repr is {repr(ex)}''')
print(f'''str is {str(ex)}''')
except Exception as e:
print("hello, world")
print(repr(e))
And the output is
(Pythonic) ➜ exception git:(master) ✗ python exception_demo.py
repr is ZeroDivisionError('division by zero')
str is division by zero
A little difference between repr(ex) and str(ex) is that repr will display the error type but str only display the error message, a little werid, right?
If you used to write Java or C# before, you may feel the lack of data in the instance of Exception, for example, the stack trace?
Luckly, there's some way we could get them, let me show you, checkout the code below.
# !/usr/bin/python
import traceback
def test():
try:
a = 10 / 0
except ZeroDivisionError as p:
print(f'''repr is {repr(p)}''')
print(f'''str is {str(p)}''')
print(traceback.format_exc())
except Exception as e:
print("hello, world")
print(repr(e))
test()
You could import traceback module to do this for you, got more infomation about exception.
(Pythonic) ➜ exception git:(master) ✗ python exception_demo.py
Traceback (most recent call last):
File "exception_demo.py", line 7, in test
a = 10 / 0
ZeroDivisionError: division by zero
See? More details, and there's an option for this function, you could using sys.exc_info() too.
import traceback
import sys
def test():
try:
a = 10 / 0
except ZeroDivisionError as p:
exc_type, exc_value, exc_traceback = sys.exc_info()
trace = traceback.format_exception(
exc_type, exc_value, exc_traceback
)
print(trace)
except Exception as e:
print("hello, world")
print(repr(e))
What's output about this code? you could find out your self, lol.
2. How to load local dependency in requirement
Sometime we need to load local project as dependecy in python project, we could try this:
--extra-index-url https://repository.xxxxx.com/artifactory/api/pypi/pypi/simple
-e ../[your project]/.
tornado==4.5.3
pycodestyle<2.4.0,>=2.0.0
pytest-tornado==0.4.5








网友评论