2016-01-11_11S_06day

一、JSON序列化

1、为什么要使用JSON:不同程序之间或不同语言之间内存数据的交互

在不同程序语言或程序之间交互数据的时候,数据的格式只有字符串格式的才可能被对端程序识别,而事实上,在数据交互的时候,大多数数据的数据类型是很复杂的,比如python的字典,而字典格式的数据是不能被别的程序语言识别的,那么久需要一个中间的媒介做翻译的功能,被该媒介翻译的数据的格式可以被其他程序识别,这种媒介就叫做JSON,类似于以前常见的XML,翻译数据的过程叫做序列化。

被JSON翻译之后任何数据都会转换为字符串类型,可以在网络(网络中只能传输字符串或二进制文件)中传输。字符串是所有程序都有的。

在将数据存入硬盘中(写入文件)的时候,数据的格式也必须是字符串格式的,JSON序列化之后的数据可以被写入文件当中。

dumps

name = {‘name‘:‘Charles‘}
import json
f  = file(‘data_to_qq‘,‘wb‘)
name_after_transfer = json.dumps(name,f)
print type(name_after_transfer)
f.write(name_after_transfer)
f.close()

E:\python\python.exe E:/python_scripts/11S_06day/json_file.py
<type ‘str‘>      #被JSON dumps之后的数据类型为字符串

文件:data_to_qq
{"name": "Charles"}

f = file(‘data_to_qq‘,‘rb‘)
import json
name = json.loads(f.read())
f.close()
print name
print name[‘name‘]

E:\python\python.exe E:/python_scripts/11S_06day/qq_app.py
{u‘name‘: u‘Charles‘}
Charles

loads

JSON的局限性:对于复杂的数据格式,如datetime.datetime.now(),JSON不能序列化。

2、dump/load和dumps/loads的区别:

dump直接将序列化的后的内容写入文件,而dumps是将序列化后的内容通过f.write()方法写入文件中,load/loads道理相同:

import json
with open(‘data_to_qq‘,‘wb‘) as f:
    json.dump(name,f)

with open(‘date_to_qq‘,‘wb‘) as f:
    name_after_transfer = json.dumps(name)
    f.write(name_after_transfer)

print json.dumps(name)
print type(json.dumps(name))

dump&dumps

import json
with open(‘data_to_qq‘,‘rb‘) as f:
    name = json.loads(f.read())
print name
print name[‘name‘]

import json
with open(‘data_to_qq‘,‘rb‘) as f:
    name = json.load(f)
print name
print name[‘name‘]

load&loads

3、pickle序列化

pickle只是针对python的,可以序列化几乎python的数据类型

二、subprocess模块

import subprocescmd = subprocess.check_output(["dir"],shell=True)   #和.call方法类似,只是call方法在命令执行错误的时候不会报错,而check_out会报错;
cmd_res = subprocess.call(["dir"],shell=True)  #类似于os.system()方法

####################### subprocess.call############################

>>> res = subprocess.call("ls -l",shell=True)  #shell=True表示允许shell命令为字符串形式,如果是这样,那么前面的shell命令必须为一条命令
总用量 13296
-rw-r--r-- 1 root root 4 12月 5 06:07 456
>>> print res
0

>>> res = subprocess.call(["ls", "-l"],shell=False)      #shell=False,相当于将前面的字符串采用了.join方法
总用量 13296
-rw-r--r-- 1 root root 4 12月 5 06:07 456
>>> print res
0

#######################subprocess.check_call######################

>>> subprocess.check_call(["ls","-l"])        
总用量 13296
-rw-r--r-- 1 root root 4 12月 5 06:07 456

0
>>> subprocess.check_call("exit 1",shell=True)    #执行命令,如果执行状态码为0,则返回0,否则抛出异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 511, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command ‘exit 1‘ returned non-zero exit status 1

>>> subprocess.check_call("exit 0",shell=True)
0

#######################subprocess.Popen############################


终端输入命令:分类

1、输入即可输出,如ifconfig

2、输入进入某环境,依赖该环境再输出

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write(‘print 1 \n ‘)
obj.stdin.write(‘print 2 \n ‘)
obj.stdin.write(‘print 3 \n ‘)
obj.stdin.write(‘print 4 \n ‘)
obj.stdin.close()

cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()

print cmd_out
print cmd_error

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write(‘print 1 \n ‘)
obj.stdin.write(‘print 2 \n ‘)
obj.stdin.write(‘print 3 \n ‘)
obj.stdin.write(‘print 4 \n ‘)

out_error_list = obj.communicate()  #communicate方法可以输出标准输出和错误输出,添加到列表中
print out_error_list

import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_error_list = obj.communicate(‘print "hello"‘)   #communicate方法可以输出
print out_error_list

>>> obj = subprocess.Popen(["python"],stdin = subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

>>> obj.stdin.write(‘print 1 \n‘)
>>> obj.stdin.write(‘print 2 \n‘)
>>> obj.stdin.write(‘print 3 \n‘)
>>> obj.stdin.write(‘print 4 \n‘)
>>> obj.stdin.close()

>>> cmd_out = obj.stdout.read()
>>> obj.stdout.close()
>>> cmd_error = obj.stderr.read()
>>> obj.stderr.close()

>>> print cmd_out
1
2
3
4
>>> print cmd_error

>>> obj = subprocess.Popen(["python"],stdin = subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> out_error_list = obj.communicate(‘print "hello"‘)
>>> print out_error_list
(‘hello\n‘, ‘‘)

三、Shutil模块

高级的文件、文件夹、压缩包处理模块

shutil模块对压缩包的处理是调用ZipFile 和TarFile模块进行的

四、日期模块

对时间的操作,有三种方式:

import time
print time.time()    #时间戳,即1970年1月1日起的秒数
print time.strftime("%Y-%m-%d")    #结构化的字符串
print time.localtime()    #结构化时间,包含年、日、星期等

E:\python\python.exe E:/python_scripts/11S_06day/time_file.py
1452996161.57
2016-01-17
time.struct_time(tm_year=2016, tm_mon=1, tm_mday=17, tm_hour=10, tm_min=2, tm_sec=41, tm_wday=6, tm_yday=17, tm_isdst=0)

  

import time
print time.time()  #打印时间戳

import datetime
print datetime.datetime.now()

E:\python\python.exe E:/python_scripts/11S_06day/time_file.py
1452695581.91
2016-01-13 22:33:01.911000

#############################
转为之间戳:可以设定格式
print time.strftime("%Y-%m-%d %H-%S")
2016-01-13 22-51
#############################
字符串转为日期
t = time.strftime("2015-09-19","%Y-%m-%d")

############################
日期的加减(只能针对天、小时和分钟)
print datetime.datetime.now() - datetime.timedelta(days=3)#和下一条效果相同
print datetime.datetime.now() + datetime.timedelta(days=-3)
print datetime.datetime.now() - datetime.timedelta(hours=3)
print datetime.datetime.now() - datetime.timedelta(minutes=3)

五、logging日志模块

CRITICAL = 50                      #日志的等级
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

  

用于便携记录日志和线程安全的(在多线程写日志的情况下,不会造成死锁)

六、re模块

###################
match  从字符串的开头匹配
>>> import re
>>> re.match("\d","abc123def") #匹配不成功无任何输出
>>> re.match(".","abc123def")  #匹配成功返回对象
<_sre.SRE_Match object at 0x0047EA30>
>>> re.match(".","abc123def").group()  #打印输出匹配到的字符串
‘a‘

###################
search 在整个字符串中匹配
>>> re.search("\d","abc123def")  #\d表示数字
<_sre.SRE_Match object at 0x0047EA30>
>>> re.search("\d","abc123def").group()
‘1‘

>>> re.search("\d+","abc123def456ghi").group()  #+号表示重复一次或更多次
‘123‘

###################
findall #找出所有符合的字符串
>>> re.findall("\d+","abc123def456ghi_*789dd")
[‘123‘, ‘456‘, ‘789‘]
>>> re.findall("[^\d+]","abc123def456ghi_*789dd")  #找出所有非数字
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘_‘, ‘*‘, ‘d‘, ‘d‘]

###################
.split #分割字符串
 re.findall("[^\d+]","abc123def456ghi_*789dd")
>>> re.split("[\d+]","abc123def456ghi_*789dd")
[‘abc‘, ‘‘, ‘‘, ‘def‘, ‘‘, ‘‘, ‘ghi_*‘, ‘‘, ‘‘, ‘dd‘]
>>> re.split("\d+","abc123def456ghi_*789dd")  #以数字进行分割
[‘abc‘, ‘def‘, ‘ghi_*‘, ‘dd‘]

>>> re.split("[\d+,\*]","abc123def456ghi_*789dd")  #以数字或*分割
[‘abc‘, ‘‘, ‘‘, ‘def‘, ‘‘, ‘‘, ‘ghi_‘, ‘‘, ‘‘, ‘‘, ‘dd‘]

###################
sub 替换
>>> re.sub("ab","YUE","abc123def456ghi_*789ddabc") #将ab替换为YUE,替换所有
‘YUEc123def456ghi_*789ddYUEc‘

>>> re.sub("ab","YUE","abc123def456ghi_*789ddabc",count=1) #count参数可以设定替换几次
‘YUEc123def456ghi_*789ddabc‘
>>> re.sub("ab","YUE","abc123def456ghi_*789ddabc",count=2)
‘YUEc123def456ghi_*789ddYUEc‘.sub包含replcce功能,replace不能替换由正则表达式匹配的字符串;

###################
匹配IP地址
>>> re.search("(\d+\.){3}(\d+)",t)
<_sre.SRE_Match object at 0x004BB020>
>>> re.search("(\d+\.){3}(\d+)",t).group()
‘192.168.72.1‘

精确匹配IP地址

>>> re.search("(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|
2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])",t).group()
‘192.168.72.1‘

###################group和groups
>>> name = ‘Charles Chang‘
>>> re.search("(\w+)\s(\w+)",name)
<_sre.SRE_Match object at 0x004BB020>

>>> re.search("(\w+)\s(\w+)",name).group()
‘Charles Chang‘

>>> re.search("(\w+)\s(\w+)",name).groups()
(‘Charles‘, ‘Chang‘)

>>> re.search("(\w+)\s(\w+)",name).groups()[0]
‘Charles‘
>>>
>>> re.search("(?P<name>\w+)\s(?P<last_name>\w+)",name) #起别名
<_sre.SRE_Match object at 0x004BB020>

>>> res = re.search("(?P<name>\w+)\s(?P<last_name>\w+)",name)

>>> res.group("name")
‘Charles‘
>>> res.group("last_name")
‘Chang‘
#####################
转义
>>> t = "\n\tabc"
>>> print t

        abc
>>> t = r"\n\tabc"
>>> print t
\n\tabc
####################
compile   事先编译,在循环调用的使用提供效率

>>> p = re.compile("\d+")
>>> re.search(p,‘12223‘)
<_sre.SRE_Match object at 0x004505D0>
>>> re.search(p,‘12223‘).group()
‘12223‘
>>> p.match(‘123‘)
<_sre.SRE_Match object at 0x004505D0>
>>> p.match(‘123‘).group()
‘123‘
>>> p.search(‘12223‘).group()
‘12223‘
>>>
split和search的区别:
inpp = ‘1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))‘

content = re.search(‘\(([\+\-\*\/]*\d+\.*\d*){2,}\)‘,inpp).group()
before,nothing,after = re.split(‘\(([\+\-\*\/]*\d+\.*\d*){2,}\)‘,inpp,1)
print before
print nothing
print content
print after

结果为:
E:\python\python.exe E:/python_scripts/11S_07day/re_file.py
[‘1-2*((60-30+‘, ‘-40-5‘, ‘*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘]
1-2*((60-30+
-5
(-40-5)
*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))

七、面向对象

################################
类初始化的两种方式:
1、
class Person(object):
    def __init__(self,name):
        self.name = name
        print "--->create:",name
    def say_name(self):
        print "My name is %s" %self.name
    def eat(self):
        print "%s is eating...." %self.name

p1 = Person("gf1")
p2 = Person("gf2")
p1.eat()

E:\python\python.exe E:/python_scripts/11S_06day/class_sample.py
--->create: gf1
--->create: gf2
gf1 is eating....
2、
class Person(object):
    def __init__(self,name):
        #self.name = name
        print "--->create:",name
    def say_name(self):
        print "My name is %s" %self.name
    def eat(self):
        print "%s is eating...." %self.name

p1 = Person("gf1")
p2 = Person("gf2")
p1.name = "GF"
p1.eat()

E:\python\python.exe E:/python_scripts/11S_06day/class_sample.py
--->create: gf1
--->create: gf2
GF is eating....
时间: 2024-08-01 17:01:32

2016-01-11_11S_06day的相关文章

[官方软件] Easy Sysprep v4.3.29.602 【系统封装部署利器】(2016.01.22)--skyfree大神

[官方软件] Easy Sysprep v4.3.29.602 [系统封装部署利器](2016.01.22) Skyfree 发表于 2016-1-22 13:55:55 https://www.itsk.com/forum.php?mod=viewthread&tid=362766&highlight=Easy%2BSysprep [官方软件] Easy Sysprep v4.3.29.602 [系统封装部署利器](2016.01.22) [Easy Sysprep]概述:Easy Sy

2016.01工作日志

2016.01.01 元旦在家,八点醒,开始继续阅读「30日でできる!OS自作入門」.主要目的,加深对os和cpu的理解.另外花些时间又重温王爽的<汇编语言>.今天,最大收获还是感官上体会系统底层:比如往内存xxxx里写入0或者1就可以实现操作系统对xxxx部件的控制.另外,看到了「30日でできる!OS自作入門」中自制操作系统的内存图,就可以知道,内存这种东西,就是操作系统,或者cpu规划的.内存本身是不分段的.内存的哪一段是ram哪一段是bios显卡,改变其地址值就可以实现特定效果. 对于这

2016.01.18-2016.01.21盲审通关修改

请以上同学在1月21日(星期四)之前将以下材料交到研究生科: 1.装订好的硕士学位论文3本(注意:封面上作者姓名和指导教师隐去.致谢隐去.硕士学位期间发表的全部的论文作者隐去): 2.普通信封上写明评阅费:200元.邮寄费:22元,并将相应的钱款分别装入以上三个信封(普通信封,一共:200*3+22*3元): 3.从研究生管理信息系统中导出的“论文评阅书”封面上的作者姓名和指导教师姓名隐去:交三份“论文评阅书”和三份“学位论文评阅聘书”. 4.交三份“EMS”信封和一个装有20×3=60元邮寄费

2016/01/14开始学习git:标签管理:创建标签

标签也是版本库的一个快照指向某个commit的指针(分支可以移动,标签不能移动) 切换到需要打标签的分支上git tag <name>就可以打一个新标签: $ git tag v1.0 git tag查看所有标签: $ git tagv1.0 打之前提交的版本的commit需要当时的commit ID$ git tag v0.9 93ddf60 查看tag$ git tagv0.9v1.0 标签不是按时间顺序列出,而是按字母排序的.可以用git show <tagname>查看标签

分布式技术一周技术动态 2016.01.17

分布式系统实践 1. Apache HBase 2015年发展回顾与未来展望 https://mp.weixin.qq.com/s?__biz=MzAwMDU1MTE1OQ==&mid=403219545&idx=1&sn=119613ae7d52de9c033b3ed0598bae6a&scene=0&key=41ecb04b05111003bd0affa70f2b91e7b66a30a4d6c249144a35c4803953e9154f772362b0679f

2016.01.21 UITabBarController

UITabBarController是IOS中很常用的一个viewController.UITabBarController通常作为整个程序的rootViewController,而且不能添加到别的container viewController中.可以轻松地管理多个控制器,轻松完成控制器之间的切换,典型的例子就是QQ.微信.微博等应?. ?.创建 在storyboard中的模拟我们就不多说了,直接进入直接代码的编写.(模拟微博的tabBarController进行编写) 我们选择在Applic

2016/01/14开始学习git:标签管理:操作标签

一.删除本地标签 如果标签打错了,也可以删除:git tag -d v0.1 因为创建的标签都只存储在本地,不会自动推送到远程.所以,打错的标签可以在本地安全删除. 二.推送标签如果要推送某个标签到远程,使用命令git push origin <tagname>:git push origin v1.0或者,一次性推送全部尚未推送到远程的本地标签:git push origin --tags 三.删除远程标签如果标签已经推送到远程,要删除远程标签就麻烦一点,先从本地删除:git tag -d

2016/01/14开始学习git:分支管理:多人协作

一.当你从远程仓库克隆时,实际上Git自动把本地的master分支和远程的master分支对应起来了,并且,远程仓库的默认名称是origin. 要查看远程库的信息,用git remote:origingit remote -v显示更详细的信息origin  [email protected]:Jacobwan/learngit.git (fetch)origin  [email protected]:Jacobwan/learngit.git (push) 二.推送分支推送分支,就是把该分支上的

2016.01.13总结

猿题库 iOS 客户端架构设计(原文地址:http://gracelancy.com/blog/2016/01/06/ape-ios-arch-design/)

猿题库 iOS 客户端架构设计 序 猿题库是一个拥有数千万用户的创业公司,从2013年题库项目起步到2015年,团队保持了极高的生产效率,使我们的产品完成了五个大版本和数十个小版本的高速迭代.在如此快速的开发过程中,如何保证代码的质量,降低后期维护的成本,以及为项目越来越快的版本迭代速度提供支持,成为了我们关注的重要问题.这篇文章将阐明我们在猿题库 iOS 客户端的架构设计. MVC MVC,Model-View-Controller,我们从这个古老而经典的设计模式入手.采用 MVC 这个架构的