lx86 发表于 2018-8-22 09:43:36

异常处理、模块包、时间模块、subprocess(调用shell命令)

异常处理
  捕捉异常可以使用try/except语句。
  try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
  如果你不想在异常发生时结束你的程序,只需在try里捕获它。
  更多的异常关键字:
  http://www.runoob.com/python/python-exceptions.html
  Exception:常规错误的基类
  IOError:输入/输出操作失败
  例子1:写入信息到tt.txt文件中,如果报错,就打印错误
  

try:  with open('tt.txt') as fd:
  fd.write('123\n456')
  
except IOError as t:
  print('Error:该文件不存在')
  
else:
  print('写入成功')
  

  例子2:
  通过json对象返回
  

import json  
def test():
  result = dict()
  try:
  print(2/0)
  except Exception as a:
  result["msg"] = "除数不能为0"
  result["code"] = 403
  result["data"] = [{"a": 1}, {"b": 2}]
  finally:
  print(type(json.dumps(result)))
  json_str=json.dumps(result,ensure_ascii=False)
  return json_str
  

  
if __name__ == '__main__':
  print(test())
  

模块包的导入
  from 目录名 import 函数名
  调用:
  函数名.函数(方法)
  新建模块包:
  1、新建一个product_oss 项目目录
  2、新建一个模块包为test1,里面多了一个init.py 的空的文件

  3、在test1 目录中新建main.py
  def add_num(x,y):
  return x + y
  if name == 'main':
  add_num(1,2)
  4、在product_oss 目录下新建 test.py
  5、目录结构如下:

  6、在test.py 中到导入main.py 的方法
  from test1 import main as tt
  print(tt.add_num(10,10))

时间模块
  1、导入模块
  from datetime import datetime, timedelta
  2、print(datetime.now())
  2018-04-28 12:14:21.867118    #年-月-日 小时:分钟:秒:毫秒
  3、显示年-月-日,小时,分钟,秒,毫秒
  print(datetime.now().year)
  print(datetime.now().month)
  print(datetime.now().day)
  print(datetime.now().hour)
  print(datetime.now().minute)
  print(datetime.now().second)
  print(datetime.now().microsecond)
  4、显示年月日-小时-分钟-秒
  print(datetime.now().strftime("%Y-%m-%d_%H:%M:%S"))
  2018-04-28_12:17:03
  5、后3个小时
  In : nowTime = datetime.now()
  In : nowTime += timedelta(hours=+3)
  In : print(nowTime)
  2018-04-28 17:33:19.152888
  time模块
  In : import time
  时间戳:从1970-01-01 开始,到现在的秒数
  In : print(time.time())
  1524897275.16
  In : print(time.ctime())
  Sat Apr 28 14:35:14 2018
  调用linux系统的命令
  标准输出传给管道(PIPE)
  from subprocess import Popen,PIPE
  In : subprocess.call('ls /root',shell=True)
  123.txt anaconda-ks.cfg python shell test venv
  Out: 0
  In : PP=Popen(['ls','/root'],stdout=PIPE)
  In : tt=PP.stdout.read().strip()
  In : tt
  Out: '123.txt\nanaconda-ks.cfg\npython\nshell\ntest\nvenv'


页: [1]
查看完整版本: 异常处理、模块包、时间模块、subprocess(调用shell命令)