Python 备忘录

*python 执行系统命令
os.popen(cmd)
不仅执行命令而且返回执行后的信息对象 (常用于需要获取执行命令后的返回信息)

import os
nowtime = os.popen('date')
print nowtime.read()
# 2016年 06月 30日 星期四 19:26:21 CST

一行代码获取当前日期时间字符串

import datetime
return str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

PythonCopy

解决图片下载损坏问题

import urllib2
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) \
    AppleWebKit/537.36 (KHTML, like Gecko) \
        Chrome/35.0.1916.114 Safari/537.36',
    'Cookie': 'AspxAutoDetectCookieSupport=1'
}
request = urllib2.Request(url, None, header)
response = urllib2.urlopen(request)
with open("D:\zdq\imgs\%s.jpg" % path_name, "wb") as f:
    f.write(response.read())

PythonCopy

发邮件

from_addr = '[email protected]' #发件人列表
password = '******' #密码,也许是授权码
smtp_server = 'smtp.xxx.com' 

tolist = ['[email protected]', '[email protected]'] #收件人列表

title = '这是邮件标题'
body = '这是正文内容'

msg = MIMEText(body, 'html', 'utf-8')  #html表示以html方式去解析body
msg['From'] = from_addr 
msg['To'] = ",".join(tolist) 
msg['Subject'] = Header(title, 'utf-8').encode()    
server = smtplib.SMTP_SSL(smtp_server, 465)   #邮箱smtp模式和端口 

server.login(from_addr, password) 
server.sendmail(from_addr, tolist, msg.as_string()) 
server.quit()

PythonCopy

获取今天字符串

import datetime
datetime.date.today().strftime('%Y%m%d')

PythonCopy

获取昨天字符串

def getYesterday():
    today = datetime.date.today()
    yesterday = today - datetime.timedelta(days=1)
    return yesterday

PythonCopy

requests 用法总结

import requests
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
rsp = requests.get(url,headers=headers)

PythonCopy

下载文件

import urllib
urllib.urlretrieve(url, local_path)

PythonCopy

禁用安全认证

from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

PythonCopy

时间戳转换

import time  
  
timeStamp = 1381419600  
timeArray = time.localtime(timeStamp)  
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)  
otherStyletime == "2013-10-10 23:40:00"  

PythonCopy

解决中文乱码

# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')

PythonCopy

解决 UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

a.encode('utf-8').strip()

PythonCopy

拷贝文件

import os
import shutil

shutil.copyfile(源文件, 目标文件) #拷贝文件
os.chown(path, gid, uid) #改变文件所有者
© 版权声明
THE END
喜欢就支持一下吧
点赞0赞赏 分享