Python3 模块库

作者: 坚持到底v2 | 来源:发表于2019-01-11 00:00 被阅读1次

    1. sys 模块

    import sys
    
    print(sys.ps1)
    # 输出 ''
    
    print(sys.ps2)
    # 输出 '... '
    
    sys.ps1='C> '
    print(sys.argv)
    sys.stderr.write('error output')
    

    2. os 模块

    import os;
    os.getcwd()  
    os.system('mkdir today')
    

    3. shell util 模块

    import shutil
    shutil.copyfile('data.db','archive.db')
    

    4. 文件通配符 glob

    import glob
    
    # 返回当前目录下所有.py文件(不包含子文件夹)
    glob.glob('*.py') 
    

    5. 正则表达式 re

    import re
    re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
    re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
    

    6. 数学 math

    import math
    

    7. 访问互联网

    from urllib.request import urlopen
    for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
         line = line.decode('utf-8')
         if 'EST' in line or 'EDT' in line:
           print(line)
    

    访问互联网 另一种写法

    from urllib import request
    with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
         data = f.read()
         print('Status:', f.status, f.reason)
         for k, v in f.getheaders():
           print('%s: %s' % (k, v))
         print('Data:', data.decode('utf-8'))
    

    访问互联网 另一种写法

    from urllib import request
    req = request.Request('http://www.douban.com/')
    req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
    with request.urlopen(req) as f:
          pass
    

    访问互联网 另一种写法

    from urllib import request, parse
    print('Login to weibo.cn...')
    email = input('Email: ')
    passwd = input('Password: ')
    login_data = parse.urlencode([
         ('username', email),
         ('password', passwd),
         ('entry', 'mweibo'),
         ('client_id', ''),
         ('savestate', '1'),
         ('ec', ''),
         ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
       ])
    
    req = request.Request('https://passport.weibo.cn/sso/login')
    req.add_header('Origin', 'https://passport.weibo.cn')
    req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
    req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
    with request.urlopen(req, data=login_data.encode('utf-8')) as f:
           pass
    

    访问互联网 通过代理访问

    proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
    proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
    proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
    opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
    with opener.open('http://www.example.com/login.html') as f:
          pass
    

    8. 发送邮件 smtplib

    import smtplib
    server = smtplib.SMTP('localhost')
    server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
         """To: jcaesar@example.org
         From: soothsayer@example.org
     
         Beware the Ides of March.
         """)
    server.quit()
    

    9. 日期和时间 datetime

    from datetime import date
    now = date.today()
    datetime.date(2003, 12, 2)
    now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
    birthday = date(1964, 7, 31)
    age = now - birthday
    age.days
    

    10. 压缩 zlib

    import zlib
    s = b'witch which has which witches wrist watch'
    t = zlib.compress(s)
    zlib.decompress(t)
    zlib.crc32(s)
    

    11. json处理

    Python3 中可以使用 json 模块来对 JSON 数据进行编解码,它包含了两个函数:

    • json.dumps(): 对数据进行编码。
    • json.loads(): 对数据进行解码。

    在json的编解码过程中,python 的原始类型与json类型会相互转换,具体的转化对照如下:

    • python中的 dict 对应 jsonObject
    • python中的 list, tuple 对应 jsonArray , 反之对于 list
    • python中的 str 对应 string
    • python中的 int, float, int- & float-derived Enums 对应 number , 反之对应 int / float
    • python中的 True / False 对应 true/false
    • python中的 None 对应 null

    示例:

    #!/usr/bin/python3
    import json 
    # Python 字典类型转换为 JSON 对象
    data = {
        'no' : 1,
        'name' : 'Runoob',
        'url' : 'http://www.runoob.com'
    }
    
    # 将dict转成字符串
    json_str = json.dumps(data)
    print("Python 原始数据:", repr(data))
    print("JSON 对象:", json_str)
    
    # 将 字符串 转换为 Python 字典
    data2 = json.loads(json_str)
    print("data2['name']: ", data2['name'])
    print("data2['url']: ", data2['url'])
    

    如果你要处理的是文件而不是字符串,你可以使用 json.dump()json.load() 来编码和解码JSON数据。例如:

    # 写入 JSON 数据
    with open('data.json', 'w') as f:
        json.dump(data, f)
     
    # 读取数据
    with open('data.json', 'r') as f:
        data = json.load(f)
    

    相关文章

      网友评论

        本文标题:Python3 模块库

        本文链接:https://www.haomeiwen.com/subject/pzxtdqtx.html