Home  >  Article  >  Backend Development  >  在同一台电脑下如何进行 Python 2 与 3 的切换?

在同一台电脑下如何进行 Python 2 与 3 的切换?

WBOY
WBOYOriginal
2016-06-06 16:22:581590browse

老师用的是 Python 2,但是我觉得自己现在学的话学个新点儿的比较好,2 和 3 据说差别还挺大,所以两个版本都装了,自己学的时候用 3,跑老师的程序时用 2。
我的电脑是 Win 7,现在系统默认调用的是 2,如果在执行前加上“C:\python33\python.exe”就可以调用 3,但是这样太麻烦了,我在环境变量的 path 中加入“C:\python33”也没有效果,不知道还应该怎么设置可以方便的进行切换?

回复内容:

好吧,我来给题主介绍个神器,virtualenv,能创建若干相互隔离的python workspace,不仅能指定python版本,连packages都能不同。
撸过几个开源的python项目别人都推荐用这个。
How to use Python virtualenv
Use different Python version with virtualenv Windows 上的 Python 自带启动器 py.exe,默认安装到系统盘的 system32 文件夹里。如果你同时安装了 Python 2 和 Python 3,用的时候直接在终端里输入:
<code class="language-text">py -3
</code>
1.
virtualenv
这基本是python开发的标配,然后你就可以控制在一个目录下用一套python环境

2.
PyScripter也是有切换python版本的功能 你可以把python3里的python.exe文件改名为python3.exe
这样的话2和3的执行命令能够分开了,也就能够实现你切换的需要了 为什么我在 Windows 上安装的时候都是环境变量都是自动写入的? 有一个很通用的解决方法,原理详见3. Using Python on Windows
python3.3或更高版本在安装时会同时把py.exe 和 pyw.exe 运行器复制到系统目录%SYSTEMROOT% 下。

如果你平时通过命令行运行python那么只要执行时,输入
<code class="language-text">py filename.py
或者
py -3 filename.py
</code>
Python 3.3 提供了一个新的Launcher来解决Windows上面的版本切换问题.

官方描述:
The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version. reference: 3. Using Python on Windows

简单的说, 在安装了Python 3.3的基础上, 保证py在环境变量中. 从命令行调用python:
<code class="language-text">py -2.7
py -3
</code>
裝兩個比如路徑
D:\python27
D:\python35

然後去手動把 python27下面的python.exe改成python2.exe
python35下面的python.exe改成python3.exe

然後你的腳本第一行就加上類似
#! D:\python27\python2.exe
這樣的一行就是調用python2
要調用python3同理 我提供一个办法 首先装一个软件 Enthough Canopy, 这是有一个带有各种科学计算python库的发行版本,诸如panda,numpy 还有各种画图库都内置了很方便。

Canopy中还集成了Pyhton包的在线升级和管理系统,很是方便。由于是商业级别的,Canopy的性能和稳定性很好。也提供免费的free版本和学术版本(用于教育科研也是免费的)。

以前叫EPD,现在改名叫Canopy。Canopy是第一个将Ipython升级到2.3.0的发行版;MatPlotLib已升级到1.4.2;NumPy 1.8.1;Scipy 1.2.0. 但是它主要是追求性能和稳定性,所以不能指望所有的安装包都是最新的。

如果你有学校邮箱的话,可以免费用商业版一年,如果没有也无妨,免费的库也很好用,而且题目本身问的是如何2.7和3.5同时安装,所以免费版就够了。canopy 是基于2.7的, 有32位和64位可选。装好之后,会有一个dos命令行的运行图标, 在同一台电脑下如何进行 Python 2 与 3 的切换?
这时,再自行去装python3.5版本即可,从一般命令行dos或者powershell进入就是3.5了。两者互不影响,库资源也都是独立的。这应该是比较好的解决方案了。
在同一台电脑下如何进行 Python 2 与 3 的切换? 如果老师要求的Python2是指Python2.7的话,你完全可以写出Python2和Python3几乎完全兼容的代码。

技巧是写『向前兼容』的代码。 Writing Forwards Compatible Python Code

实际应用过程中不是你写一份代码自己跑两遍,而是用Unit test在多个Python interpreter里自动跑。我看了一下PyCharm是支持配置多份test,每个test对应一个interpreter的。不清楚的看一下 How to Get Started with PyCharm and Have a Productive Python IDE 这里的Unittest章节。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn