1、PyCharm配置模板

    file------settings-----editer-----filie*--------templates------python script

    添加

    #!/usr/bin/env python

    # -*- coding:utf-8 -*-

    #Writed by liyang

    这样,创建同样文件的时候,会自动添加这些内容到新建文件


2、小练习:生成字典

    文件内容:

    alex|123|1

    eric|123|1

    emmy|123|1


    obj = file('log','r')  #打开文件

    line_list = obj.readlines()   #按行读入文件,生成列表

    obj.close()

    

    print line_list

    

    #处理列表

    for line in line_list:

     line.strip()

     #分割列表

     ele_list = line.split('|')

     #生成字典

     dic[ele_list[0]] = ele_list[1:]

    

dic = {}


    obj = file('C:\Users\LiYang\Desktop\Day3\log.txt','r')

    line_list = obj.readlines()

    obj.close()

    

    for line in line_list:

        line = line.strip()

        ele_list = line.split('|')

    

        dic[ele_list[0]] = ele_list[1:]

    

    print dic

3、collection系列

    import collections

    c1 = collections.Counter('asd')

    print c1


    计数器

    class Counter(dict)表示此类事扩展字典类型的

    

    elements()-----迭代器--------循环查看内容

    

    Counter中加列表

    c1 = collections.Counter()

    li = [11,22,33,12412,1,23,4]

    c1 = collections.Counter(li)

    

    import collections

    

    c1 = collections.Counter()

    

    li = [11,22,33,12412,1,23,4]

    

    c1 = collections.Counter(li)

    print c1


    c1 = collections.Counter('1233413412341234345345')

    print c1

    

    有序字典

    orderedDict

    记录字典添加的顺序

    内部结构添加列表项功能记录顺序

    有序字典只记录第一层的内容keys,exclude values



    默认字典

    defaultdict

    判断字典values是否是列表,默认类型是none

    默认字典既是指定默认类型的

    

    dic = {'k1':[]}

    my_dict = collections.defaultdict(dict)

    


    可命名元组

    namedtuple

    可命名元组使用步骤

    1、创建类

    2、使用类创建对象

    3、使用对象

    import collections

    #创建一个扩展tuple的类,Mytuple

    Mytuple = collections.namedtuple('Mytuple',['x', 'y', 'z'])

    old = tuple(1,2) <==> old = (1,2)

    

    new = Mytuple(1,2) 类似{x:1, y:2}

    print new   显示Mytuple(x=1,y=2)




    双向队列

    双向操作

    线程安全

    append

    pop从队列中去除并删除(默认从右侧)

    remove

    reverse

    

    >>> q = collections.deque(

    >>> q.append(1)

    >>> q.append(12)

    >>> q.append(123)

    >>> q.append(1234)

    >>> q

    deque([1, 12, 123, 1234])

    >>> q.pop()

    1234

    >>> q

    deque([1, 12, 123])

    

    示例,生产者---消费者模型



    Queue   单项队列

    >>> import Queue

    >>> q = Queue.Queue(10)

    >>> q

    <Queue.Queue instance at 0x00000000021867C8>

    >>> q.put(1)

    >>> q.put(2)

    >>> q.put(3)

    >>> q.put(4)

    >>> q.get()

    1

    >>> q.get()

    2

    >>> q.get()

    3

    >>> q.get()

    4

    >>> q.get()


    先进先出是单向队列的特点

    先进后出是栈的特点,弹夹



    迭代器

    

    生成器

    >>> print range(10)

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    >>> print xrange(10) 使用时才会用

    xrange(10)

    

    数据库链接池可用生成器创建

    线程池也可以

    

    for i in range(len(li))

     print li[i]

    

    下标循环

    值得替换

    冒泡排序

    li = [13, 22, 6, 99, 11]

    

    for m in range(len(li)-1):

    

        for n in range(m+1, len(li)):

            if li[m]> li[n]:

                temp = li[n]

                li[n] = li[m]

                li[m] = temp

    

    print li

    

    深浅拷

    

    函数:内置函数,自定义函数,导入函数

    

    按功能划分的代码块

    vars()显示变量

    

    __file__文件路径

    __doc__注释

    模块的注释可以再PC中Ctrl+左键查看Queue.__doc__

    

    __name__ : __main__ 显示主函数、

    表示程序主模块的位置,程序入口文件

    

    reload(temp)

    

    id内存地址

    is地址比较

    

    cmp

    abs

    bool

    divmod 商加余数

    max

    min

    sum

    pow(2,11)指数

    计算



    len

    all,接受序列,内部判断,如果所有值为真,返回真,否则返回假

    

    any,有一个值为真则返回true

    >>> li = [1,'',21]

    >>> all(li)

    False

    >>> li = [1,'li',21]

    >>> all(li)

    True

    >>> any(li)

    True

    >>> li = [1,'',21]

    >>> any(li)

    True

    >>> all(li)

    False



    chr chr(65)-------A

    ord ord('A')------65

    做数字字符(ASCII)转换

    

    hex

    oct

    bin

    

    enumrate

    

    >>> li = [11,22,33,44,55]

    

    >>> for k,v in enumerate(li):

    ...     print k,v

    ...

    0 11

    1 22

    2 33

    3 44

    4 55

    

    >>> for k,v in enumerate(li,1):

    ...     print k,v

    ...

    1 11

    2 22

    3 33

    4 44

    5 55



    重点,下节介绍

    map

    group

    reduce

    filter

    apply

    





    """

    import collections

    

    mytuple = collections.namedtuple('mytuple',['x','y'])

    

    new = mytuple(1,2)

    

    print new

    print new.x

    print new.y

    

    print vars()

    print __doc__

    print __name__

    print __file__

    自定义函数

    参数

    def email(arg):

        print arg

    

    if __name__ == "__main__":

        cpu = 100

        disk = 200

        ram = 30

    

        if cpu > 90:

                alert = "CPU Problem"

                email(alert)

    

        if disk > 100:

                alert = "Disk Problem"

                email(alert)

        if ram > 100:

                alert = "Memory Problem"

                email(alert)

    

    

        发送邮件实例

    import smtplib

    from email.mime.text import MIMEText

    from email.utils import formataddr

    ?

    ?

    msg = MIMEText('邮件内容', 'plain', 'utf-8')

    msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])

    msg['To'] = formataddr(["走人",'424662508@qq.com'])

    msg['Subject'] = "主题"

    ?

    server = smtplib.SMTP("smtp.126.com", 25)

    server.login("wptawy@126.com", "邮箱密码")

    server.sendmail('wptawy@126.com', ['424662508@qq.com',], msg.as_string())

    server.quit()

    




    #!/usr/bin/env python

    # -*- coding:utf-8 -*-

    # Writed by liyang

    import smtplib

    from email.mime.text import MIMEText

    from email.utils import formataddr

    

    def email(arg):

        msg = MIMEText(arg, 'plain', 'utf-8')

        msg['From'] = formataddr(["liyang",'819233578@qq.com'])

        msg['To'] = formataddr(["admin",'liyang215601@yeah.net'])

        msg['Subject'] = "oldboy"


        server = smtplib.SMTP("smtp.126.com", 25)

        server.login("819233578@qq.com", "liyang215601@yeah.net")

        server.sendmail('819233578@qq.com', ['liyang215601@yeah.net',], msg.as_string())

        server.quit()

    

    if __name__ == "__main__":

        cpu = 100

        disk = 200

        ram = 30

    

        if cpu > 90:

                alert = u"CPU Problem"

                email(alert)

    

        if disk > 100:

                alert = u"Disk Problem"

                email(alert)

        if ram > 100:

                alert = u"Memory Problem"

                email(alert)

    

    改进

     发送失败重发,并记录到日志失败信息

    

     return返回值

     默认函数返回值是none

    

    参数

     普通参数

     默认参数

     动态参数

    普通参数

    形式参数,定义不赋值

    实际参数,函数调用时,传入的参数

    

    

    收件人支持列表********

    

    多个参数

    

    默认参数*********

        

    

    动态参数

    



    func(*arg)------动态参数

    >>> li = (11,22,33,44,55)

    >>> def func(*arg):

    ...     print arg

    ...

    >>> func()

    ()

    >>> func(li)

    ((11, 22, 33, 44, 55),)

    >>> func(*li)

    (11, 22, 33, 44, 55)

    >>> tu = [11,22,33,44,55]

    >>> func(*tu)  #传入列表,转换结果是元组

    (11, 22, 33, 44, 55)

    

    接受多个参数

    内部自动构造元组

    序列,*, 避免内部构造元组

    

    >>> def func(*arg):

    ...     print arg[0]

    ...

    >>> func(11,22,33)

    11

    >>>



    字典构造

    >>> func(k1=123)

    {'k1': 123}

    >>> func(k1=123,k2=999)

    {'k2': 999, 'k1': 123}

    >>> dic = {'k1':123, 'k2':123123}

    >>> func(**dic)

    {'k2': 123123, 'k1': 123}

    

    混合使用  元组加字典

    >>> def func(*args,**kwargs):

    ...     print args

    ...     print kwargs

    ...

    >>> func(11,22,33)

    (11, 22, 33)

    {}

    >>> func(k1=13,k2=123)

    ()

    {'k2': 123, 'k1': 13}

    >>> func(1,2,3,k1=13,k2=123)

    (1, 2, 3)

    {'k2': 123, 'k1': 13}

    >>> func(1,2,3,k1=13,k2=123)

    (1, 2, 3)

    {'k2': 123, 'k1': 13}

    >>> func(1,2,3,k1=13,k2=123,9)

      File "<stdin>", line 1

    SyntaxError: non-keyword arg after keyword arg

    




    str.format既是上述示例

    字符串格式化:

    1、

    >>> name = 'i am {0},age {1}'

    >>> name.format('alex','30')

    'i am alex,age 30'

    2、

    >>> name = 'i am {ss},age {dd}'

    >>> name.format(ss='alex',dd='23')

    'i am alex,age 23'

    >>> name.format(dd='23',ss='alex')

    'i am alex,age 23'

    3、

    li = ['alex',23]

    name.format(*li) # 传一列表或者元组要在其前面加*

    4、

    dic = {'ss':123,'dd':456}}

    name= "i m {ss},age {dd}"

    name.format(**dic)

    

    

4、文件操作

    推荐open打开文件

    

    seek()  起始位置,多少个字节

    tell()  显示当前指针

    从第二行开始,先确定换行位置

    

    图片

    

    obj = open('C:\Users\LiYang\Desktop\Day3\log.txt','r')

    obj.seek(2)

    print obj.tell()

    print obj.read()

    print obj.tell()

    

    a 模式,指针在文件结尾,自动转至结尾

    r+ 可读可写,有意义

    obj = open('C:\Users\LiYang\Desktop\Day3\log.txt','r+')

    obj.write('000')

    obj.truncate()

    

    

    with open('log','r') as obj:

     obj.write(xxxxxx)

    

    2.7之后支持,同时打开多个文件

    在线修改nginx配置文件,可以回滚,同时打开两个文件