2015年10月26日星期一

PYTHON编程技巧总结【2】

Commands in this section:
   assert Expression[, Arguments]
  type('a') == types.StringType
   subprocess.call / os.system
   profile cprofile pstats
   Python decorators



quite similar with "if condition: Do()"
assert 2 + 2 == 5, "Houston we've got a problem"
types.StringType can be used to check whether a variation is a STR.

Run C commands or other shell based commands using subprocess.call/os.system. Get the return values with subprocess.stdout
subprocess.call("exit 1", shell=True)

profile, cProfile, and pstats – Performance analysis of Python programs (website)


Decorators (website )
class safe:
  def __init__(self, function):
    self.function = function

  def __call__(self, *args):
    try:
      return self.function(*args)
    except Exception, e:
      print "Error: %s" % (e)
@safe
def unsafe(x):
  return 1 / x

print "unsafe(1): ", unsafe(1)
print "unsafe(0): ", unsafe(0)