python常用代码段

requests爬取图片

import requests

url = 'https://www.baidu.com/img/bd_logo1.png'
data = requests.get(url).content
with open('baidu.png', 'wb') as fb:
    fb.write(data)

uuid

from uuid import uuid4
print(uuid4()) # 253b0bda-7f3e-4eeb-9116-b8b4865083b6

获取cpu 内存的使用率

import psutil
import os

print(os.getpid())
print(psutil.virtual_memory().percent)
print(psutil.cpu_percent(interval=1.0))

# 40462
# 67.2
# 7.1

字典转json(解决中文乱码)

import json

dict = {
    'user': 'yubozhi',
    'title': '硬盘不是“背锅侠',
    'time': '2017-11-29'
}

print(json.dumps(dict, ensure_ascii=False))

# {"user": "yubozhi", "title": "硬盘不是“背锅侠", "time": "2017-11-29"}

你可能感兴趣的:(Python)