博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python2和Python3比较分析
阅读量:6265 次
发布时间:2019-06-22

本文共 9377 字,大约阅读时间需要 31 分钟。

一直有看到网上有讨论Python2和Python3的比较,最近公司也在考虑是否在spark-python大数据开发环境中升级到python3。通过本篇博文记录Python2.7.13和Pthon3.5.3的各方面比较。

环境配置

这里继续使用我们在里配置的环境。

因为是比较Python2和Python3差异,所以单纯升级Python版本无法解决,我通过pyenv和virtualenv两个工具来实现隔离的测试环境。
参考文档:、
配置的步骤如下:

  • 最开始是更新Tkinter,不然后续要重新再来一次,不要问我为什么知道…
 
  1. sudo yum install tkinter -y
  2. sudo yum install tk-devel tcl-devel -y
  • 更新pyenv依赖软件
 
  1. sudo yum install readline readline-devel readline-static -y
  2. yum install openssl openssl-devel openssl-static -y
  3. yum install sqlite-devel -y
  4. yum install bzip2-devel bzip2-libs -y
  • 下载安装pyenv,并下载python2.7.13和python3.5.3
 
  1. git clone https://github.com/yyuu/pyenv.git ~/.pyenv
  2. chgmod 777 -R ~/.pyenv
  3. echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
  4. echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
  5. echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
  6. exec $SHELL
  7. source ~/.bash_profile
  8. pyenv install --list
  9. pyenv install -v 2.7.13
  10. pyenv install -v 3.5.3
  • 下载安装pyenv-virtualenv,并安装两个隔离环境
 
  1. git clone https://github.com/yyuu/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv
  2. echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile
  3. source ~/.bash_profile
  4. pyenv virtualenv 2.7.13 py2
  5. pyenv virtualenv 3.5.3 py3

好,到此基本搞定两个隔离的python环境,测试如下,我们可以发现当前的python环境从centos7默认的2.7.5切换到2.7.13再切换到3.5。

 
  1. [kejun@localhost ~]$ python -V
  2. Python 2.7.5
  3. [kejun@localhost ~]$ pyenv activate py2
  4. (py2) [kejun@localhost ~]$ python -V
  5. Python 2.7.13
  6. (py2) [kejun@localhost ~]$ pyenv deactivate
  7. [kejun@localhost ~]$ pyenv activate py3
  8. (py3) [kejun@localhost ~]$ python -V
  9. Python 3.5.

详细测试:

我们安装了常用的数据分析第三方工具包,并做了安装测试和样例测试,样例测试的脚本见最下。

分类 工具名 用途
数据收集 scrapy 网页采集,爬虫
数据收集 scrapy-redis 分布式爬虫
数据收集 selenium web测试,仿真浏览器
数据处理 beautifulsoup 网页解释库,提供lxml的支持
数据处理 lxml xml解释库
数据处理 xlrd excel文件读取
数据处理 xlwt excel文件写入
数据处理 xlutils excel文件简单格式修改
数据处理 pywin32 excel文件的读取写入及复杂格式定制
数据处理 Python-docx Word文件的读取写入
数据分析 numpy 基于矩阵的数学计算库
数据分析 pandas 基于表格的统计分析库
数据分析 scipy 科学计算库,支持高阶抽象和复杂模型
数据分析 statsmodels 统计建模和计量经济学工具包
数据分析 scikit-learn 机器学习工具库
数据分析 gensim 自然语言处理工具库
数据分析 jieba 中文分词工具库
数据存储 MySQL-python mysql的读写接口库
数据存储 mysqlclient mysql的读写接口库
数据存储 SQLAlchemy 数据库的ORM封装
数据存储 pymssql sql server读写接口库
数据存储 redis redis的读写接口
数据存储 PyMongo mongodb的读写接口
数据呈现 matplotlib 流行的数据可视化库
数据呈现 seaborn 美观的数据可是湖库,基于matplotlib
工具辅助 jupyter 基于web的python IDE,常用于数据分析
工具辅助 chardet 字符检查工具
工具辅助 ConfigParser 配置文件读写支持
工具辅助 requests HTTP库,用于网络访问
 
  1. # encoding=utf-8
  2. import sys
  3. import platform
  4. import traceback
  5. import gc
  6. import ctypes
  7. STD_OUTPUT_HANDLE= -11
  8. FOREGROUND_BLACK = 0x0
  9. FOREGROUND_BLUE = 0x01 # text color contains blue.
  10. FOREGROUND_GREEN= 0x02 # text color contains green.
  11. FOREGROUND_RED = 0x04 # text color contains red.
  12. FOREGROUND_INTENSITY = 0x08 # text color is intensified.
  13. class WinPrint:
  14. """
  15. 提供给Windows打印彩色字体使用
  16. """
  17. std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
  18. def set_cmd_color(self, color, handle=std_out_handle):
  19. bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
  20. return bool
  21. def reset_color(self):
  22. self.set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
  23. def print_red_text(self, print_text):
  24. self.set_cmd_color(FOREGROUND_RED | FOREGROUND_INTENSITY)
  25. print (print_text)
  26. self.reset_color()
  27. def print_green_text(self, print_text):
  28. self.set_cmd_color(FOREGROUND_GREEN | FOREGROUND_INTENSITY)
  29. print (print_text)
  30. self.reset_color()
  31. class UnixPrint:
  32. """
  33. 提供给Centos打印彩色字体
  34. """
  35. def print_red_text(self, print_text):
  36. print('\033[1;31m%s\033[0m'%print_text)
  37. def print_green_text(self, print_text):
  38. print('\033[1;32m%s\033[0m'%print_text)
  39. py_env = "Python2" if sys.version.find("2.7") > -1 else "Python3"
  40. sys_ver = "Windows" if platform.system().find("indows") > -1 else "Centos"
  41. my_print = WinPrint() if platform.system().find("indows") > -1 else UnixPrint()
  42. def check(sys_ver, py_env):
  43. """
  44. 装饰器,统一输入输出
  45. 顺便测试带参数的装饰器,非必须带参数
  46. """
  47. def _check(func):
  48. def __check():
  49. try:
  50. func()
  51. my_print.print_green_text(
  52. "[%s,%s]: %s pass." % (sys_ver, py_env, func.__name__))
  53. except:
  54. traceback.print_exc()
  55. my_print.print_red_text(
  56. "[%s,%s]: %s fail." % (sys_ver, py_env, func.__name__))
  57. return __check
  58. return _check
  59. def make_requirement(filepath, filename):
  60. """
  61. 处理pip requirements文件
  62. """
  63. result = []
  64. with open(filepath + "\\" + filename, "r") as f:
  65. data = f.readlines()
  66. for line in data:
  67. if line.find("==") > -1:
  68. result.append(line.split("==")[0] + "\n")
  69. else:
  70. result.append(line + "\n")
  71. with open(filepath + "\\" + filename.split(".")[0] + "-clean.txt",
  72. "w") as f1:
  73. f1.writelines(result)
  74. @check(sys_ver, py_env)
  75. def test_scrapy():
  76. from scrapy import signals
  77. from selenium import webdriver
  78. from scrapy.http import HtmlResponse
  79. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  80. from selenium.webdriver.common.keys import Keys
  81. from selenium.common.exceptions import NoSuchElementException
  82. from selenium.common.exceptions import TimeoutException
  83. from selenium.webdriver.support import expected_conditions as EC
  84. from selenium.webdriver.common.by import By
  85. from selenium.webdriver.support.ui import WebDriverWait
  86. @check(sys_ver, py_env)
  87. def test_matplotlib():
  88. import matplotlib.pyplot as plt
  89. l = [1, 2, 3, 4, 5]
  90. h = [20, 14, 38, 27, 9]
  91. w = [0.1, 0.2, 0.3, 0.4, 0.5]
  92. b = [1, 2, 3, 4, 5]
  93. fig = plt.figure()
  94. ax = fig.add_subplot(111)
  95. rects = ax.bar(l, h, w, b)
  96. # plt.show()
  97. @check(sys_ver, py_env)
  98. def test_beautifulSoup():
  99. from bs4 import BeautifulSoup
  100. html_str = "<html><meta/><head><title>Hello</title></head><body onload=crash()>Hi all<p></html>"
  101. soup = BeautifulSoup(html_str, "lxml")
  102. # print (soup.get_text())
  103. @check(sys_ver, py_env)
  104. def test_lxml():
  105. from lxml import html
  106. html_str = "<html><meta/><head><title>Hello</title></head><body onload=crash()>Hi all<p></html>"
  107. html.fromstring(html_str)
  108. @check(sys_ver, py_env)
  109. def test_xls():
  110. import xlrd
  111. import xlwt
  112. from xlutils.copy import copy
  113. excel_book2 = xlwt.Workbook()
  114. del excel_book2
  115. excel_book1 = xlrd.open_workbook("1.xlsx")
  116. del excel_book1
  117. import docx
  118. doc = docx.Document("1.docx")
  119. # print (doc)
  120. del doc
  121. gc.collect()
  122. @check(sys_ver, py_env)
  123. def test_data_analysis():
  124. import pandas as pd
  125. import numpy as np
  126. data_list = np.array([x for x in range(100)])
  127. data_serial = pd.Series(data_list)
  128. # print (data_serial)
  129. from scipy import fft
  130. b = fft(data_list)
  131. # print (b)
  132. @check(sys_ver, py_env)
  133. def test_statsmodels():
  134. import statsmodels.api as sm
  135. data = sm.datasets.spector.load()
  136. data.exog = sm.add_constant(data.exog, prepend=False)
  137. # print data.exog
  138. @check(sys_ver, py_env)
  139. def test_sklearn():
  140. from sklearn import datasets
  141. iris = datasets.load_iris()
  142. data = iris.data
  143. # print(data.shape)
  144. @check(sys_ver, py_env)
  145. def test_gensim():
  146. import warnings
  147. warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
  148. from gensim import corpora
  149. from collections import defaultdict
  150. documents = ["Human machine interface for lab abc computer applications",
  151. "A survey of user opinion of computer system response time",
  152. "The EPS user interface management system",
  153. "System and human system engineering testing of EPS",
  154. "Relation of user perceived response time to error measurement",
  155. "The generation of random binary unordered trees",
  156. "The intersection graph of paths in trees",
  157. "Graph minors IV Widths of trees and well quasi ordering",
  158. "Graph minors A survey"]
  159. stoplist = set('for a of the and to in'.split())
  160. texts = [[word for word in document.lower().split() if word not in stoplist]
  161. for document in documents]
  162. frequency = defaultdict(int)
  163. for text in texts:
  164. for token in text:
  165. frequency[token] += 1
  166. texts = [[token for token in text if frequency[token] > 1]
  167. for text in texts]
  168. dictionary = corpora.Dictionary(texts)
  169. dictionary.save('deerwester.dict')
  170. @check(sys_ver, py_env)
  171. def test_jieba():
  172. import jieba
  173. seg_list = jieba.cut("我来到了北京参观天安门。", cut_all=False)
  174. # print("Default Mode: " + "/ ".join(seg_list)) # 精确模式
  175. @check(sys_ver, py_env)
  176. def test_mysql():
  177. import MySQLdb as mysql
  178. #测试pet_shop连接
  179. db = mysql.connect(host="xx", user="yy", passwd="12345678", db="zz")
  180. cur = db.cursor()
  181. sql="select id from role;"
  182. cur.execute(sql)
  183. result = cur.fetchall()
  184. db.close()
  185. # print (result)
  186. @check(sys_ver, py_env)
  187. def test_SQLAlchemy():
  188. from sqlalchemy import Column, String, create_engine,Integer
  189. from sqlalchemy.orm import sessionmaker
  190. from sqlalchemy.ext.declarative import declarative_base
  191. engine = create_engine('mysql://xxx/yy',echo=False)
  192. DBSession = sessionmaker(bind=engine)
  193. Base = declarative_base()
  194. class rule(Base):
  195. __tablename__="role"
  196. id=Column(Integer,primary_key=True,autoincrement=True)
  197. role_name=Column(String(100))
  198. role_desc=Column(String(255))
  199. new_rule=rule(role_name="test_sqlalchemy",role_desc="forP2&P3")
  200. session=DBSession()
  201. session.add(new_rule)
  202. session.commit()
  203. session.close()
  204. @check(sys_ver, py_env)
  205. def test_redis():
  206. import redis
  207. pool = redis.Redis(host='127.0.0.1', port=6379)
  208. @check(sys_ver, py_env)
  209. def test_requests():
  210. import requests
  211. r=requests.get(url="http://www.cnblogs.com/kendrick/")
  212. # print (r.status_code)
  213. @check(sys_ver, py_env)
  214. def test_PyMongo():
  215. from pymongo import MongoClient
  216. conn=MongoClient("localhost",27017)
  217. if __name__ == "__main__":
  218. print ("[%s,%s] start checking..." % (sys_ver, py_env))
  219. test_scrapy()
  220. test_beautifulSoup()
  221. test_lxml()
  222. test_matplotlib()
  223. test_xls()
  224. test_data_analysis()
  225. test_sklearn()
  226. test_mysql()
  227. test_SQLAlchemy()
  228. test_PyMongo()
  229. test_gensim()
  230. test_jieba()
  231. test_redis()
  232. test_requests()
  233. test_statsmodels()
  234. print ("[%s,%s] finish checking." % (sys_ver, py_env))

转载于:https://www.cnblogs.com/kendrick/p/6605676.html

你可能感兴趣的文章
MVC3中使用RadioButtonFor()
查看>>
单元测试的概念
查看>>
Android特效 五种Toast详解
查看>>
phpcms(4) V9 栏目管理
查看>>
php多进程pcntl学习(采集新浪微博)
查看>>
[转]ListView学习笔记(一)——缓存机制
查看>>
【完全跨域】异步上传文件并获得返回值
查看>>
【TCP/IP详解 卷一:协议】第二章:链路层
查看>>
AWS开发人员认证考试样题解析
查看>>
Linux_DHCP服务搭建
查看>>
日请求亿级的 QQ 会员 AMS 平台 PHP7 升级实践
查看>>
【Coursera】Security Introduction -Eighth Week(2)
查看>>
Vue系列:如何将百度地图包装成Vue的组件
查看>>
Charles 从入门到精通
查看>>
MVC5 + EF6 简单示例
查看>>
Mysql Innodb存储引擎 insert 死锁分析
查看>>
好的用户界面-界面设计的一些技巧
查看>>
全端开发必备!10个最好的 Node.js MVC 框架
查看>>
初始Knockout
查看>>
HADOOP 2.6 INSTALLING ON UBUNTU 14.04 (hadoop 2.6 部署到ubuntu 14.04上面)
查看>>