博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
异常处理、模块包、时间模块、subprocess(调用shell命令)
阅读量:6914 次
发布时间:2019-06-27

本文共 2095 字,大约阅读时间需要 6 分钟。

异常处理

捕捉异常可以使用try/except语句。

try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
如果你不想在异常发生时结束你的程序,只需在try里捕获它。

更多的异常关键字:

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 jsondef 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_strif __name__ == '__main__':    print(test())

模块包的导入

from 目录名 import 函数名

调用:

函数名.函数(方法)

新建模块包:

1、新建一个product_oss 项目目录

2、新建一个模块包为test1,里面多了一个init.py 的空的文件

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

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、目录结构如下:

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

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 [12]: nowTime = datetime.now()

In [13]: nowTime += timedelta(hours=+3)

In [14]: print(nowTime)

2018-04-28 17:33:19.152888

time模块

In [15]: import time

时间戳:从1970-01-01 开始,到现在的秒数

In [16]: print(time.time())
1524897275.16

In [17]: print(time.ctime())

Sat Apr 28 14:35:14 2018

调用linux系统的命令

标准输出传给管道(PIPE)

from subprocess import Popen,PIPE

In [52]: subprocess.call('ls /root',shell=True)

123.txt anaconda-ks.cfg python shell test venv
Out[52]: 0

In [47]: PP=Popen(['ls','/root'],stdout=PIPE)

In [48]: tt=PP.stdout.read().strip()
In [49]: tt
Out[49]: '123.txt\nanaconda-ks.cfg\npython\nshell\ntest\nvenv'

转载于:https://blog.51cto.com/jacksoner/2108890

你可能感兴趣的文章
Redis应用学习——Redis Cluster的集群伸缩
查看>>
pfsense远程管理
查看>>
highcharts中数据过多时,横坐标上的标签无法正常显示解决
查看>>
AWS Cloudformation的相关概念
查看>>
The type promotion rules (类型提升规则,以及类型转换规则)
查看>>
iOS开发多线程篇---多线程基础介绍和创建
查看>>
Windows Server 2012 R2在桌面上显示计算机/网络图标
查看>>
testNG
查看>>
windows7下配置nginx
查看>>
latch: library cache pin等待事件
查看>>
greenDAO系列4--构建模型
查看>>
Java多线程开发技巧
查看>>
4.MySQL Proxy
查看>>
MAC outlook achrive (导出或手动存档 Outlook 项目)
查看>>
1.1学习之初1.2约定1.3认识Linux1.4创建虚拟机1.5安装CentOS7
查看>>
ASP .NET 如何在 SQL 查询层面实现分页
查看>>
vue1和Vue2 调起tel 通话区别的写法
查看>>
剑指offer09
查看>>
在SublimeText上搭建ReactJS开发环境
查看>>
http://www.2cto.com/os/201306/220146.html
查看>>