1. 程式人生 > >Python 編程,應該養成哪些好的習慣

Python 編程,應該養成哪些好的習慣

.so bytearray bsp all sys cti nbsp sub 應該

Python 編程,應該養成哪些好的習慣? https://www.zhihu.com/question/28966220 無緩沖輸出 python -u sys.stdout.flush() 性能分析 python -m cProfile -o prof.txt my_script.py import pstats p = pstats.Stats(‘prof.txt‘) p.strip_dirs().sort_stats(‘time‘, ‘cumulative‘).print_stats() #p.strip_dirs().sort_stats(‘time‘, ‘cumulative‘).print_callees() https://docs.python.org/2/library/profile.html https://github.com/rkern/line_profiler https://stackoverflow.com/questions/582336/how-can-you-profile-a-script 導入模塊路徑 import os print os.__file__ 輸出異常行數 print >>sys.stderr, sys.exc_info()[-1].tb_lineno, str(e) 查看調用棧 ‘‘.join(traceback.format_stack(frame)) 空間使用
(ref: http://stackoverflow.com/questions/449560/how-do-i-determine-the-size-of-an-object-in-python ) import sys from numbers import Number from collections import Set, Mapping, deque try: # Python 2 zero_depth_bases = (basestring, Number, xrange, bytearray) iteritems = ‘iteritems‘ except NameError: # Python 3 zero_depth_bases = (str, bytes, Number, range, bytearray) iteritems = ‘items‘ def getsize(obj_0): """Recursively iterate to sum size of object & members.""" def inner(obj, _seen_ids = set()): obj_id = id(obj) if obj_id in _seen_ids: return 0 _seen_ids.add(obj_id) size = sys.getsizeof(obj) if isinstance(obj, zero_depth_bases): pass # bypass remaining control flow and return elif isinstance(obj, (tuple, list, Set, deque)): size += sum(inner(i) for i in obj) elif isinstance(obj, Mapping) or hasattr(obj, iteritems): size += sum(inner(k) + inner(v) for k, v in getattr(obj, iteritems)()) # Check for custom object instances - may subclass above too if hasattr(obj, ‘__dict__‘): size += inner(vars(obj)) if hasattr(obj, ‘__slots__‘): # can have __slots__ with __dict__ size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s)) return size return inner(obj_0) Immutable object
技術分享圖片

Python 編程,應該養成哪些好的習慣