安装pip
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3.8 get-pip.py
pip(3) install,完美解决 externally-managed-environment
mv /usr/lib/python3.x/EXTERNALLY-MANAGED /usr/lib/python3.x/EXTERNALLY-MANAGED.bk
pip install 出现expected ‘0.2.3’, but metadata has ‘63.4.2’
python -m pip install --upgrade --no-cache-dir --use-deprecated=legacy-resolver <your_package>
python生成requirements.txt
pip freeze > requirements.txt
使用requirements.txt
pip install -r requirements.txt
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'))
解决图片下载损坏问题
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())
发邮件
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()
获取今天字符串
import datetime
datetime.date.today().strftime('%Y%m%d')
获取昨天字符串
def getYesterday():
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
return yesterday
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)
下载文件
import urllib
urllib.urlretrieve(url, local_path)
禁用安全认证
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
时间戳转换
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"
解决中文乱码
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
解决UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xa5 in position 0: invalid start byte
a.encode('utf-8').strip()
拷贝文件
import os
import shutil
shutil.copyfile(源文件, 目标文件) #拷贝文件
os.chown(path, gid, uid) #改变文件所有者
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容