Python的帮助与调试

来自Shiyin's note
跳到导航 跳到搜索
Python file.gif


  • 在python中直接输入debug
在ipython中,程序报错之后直接输入%debug
  • run -d test.py
  • 程序中设置断点,debug
pdb.set_trace()
  • 重新载入程序
import importlib
importlib.reload(myfun)

python 代码规范

  • csst的规范教程很清楚:[1]
  • 一般都是小写,除了类的首字母和常量的定义


Exceptions

  • python3 -0
在这种模式下 __debug__ = False,
Assert False, 'error', 程序不执行“error”


  • 函数locals(),vars(),globals()
python中检测某个变量是否有定义
  1. 'var' in locals().keys()
  2. 'var' in dir()
 try: 
   print   var
 except   NameError: 
   print   'var   not   defined'

raise Eexceptions

  • TypeError
abs('hello')
  • NameError
>>>hello
  • KeyError

>>>{}['hello']

  • RuntimeError

帮助

  • help(copy.copy) #def 之后帮助
  • print(copy.__doc__)
  • print(copy.__file__) #源文件地址
  • print?
  • import module之后运行dir(module)

如何自己写帮助

def average(a, b):
   """
   Return the average value (arithmetic mean) of two numbers.
   Parameters
   ----------
   a : numeric
       A number to average.
   b : numeric
       Another number to average.
   Returns
   -------
   result : numeric
       The average of a and b, computed using ``0.5 * (a + b)``.
   Example
   -------
   >>> average(5, 10)
   7.5
   """