创客见闻录每周500字

你还在纠结电脑里如何在电脑里安装python 2和3两个版本吗

2016-10-03  本文已影响2124人  少儿创客

提供python2和3在电脑共存的终极解决方案。

参考:http://stackoverflow.com/questions/15912063/how-do-i-run-python-2-and-3-in-windows-7/17245543#17245543

上文介绍了一种更好的让Python 2和Python 3在电脑里共存的方式,windows版本Python 3.3引入了Python加载器。
3.3及其以上版本安装的时候把py.exe和pyw.exe复制到了c:\windows目录,所以即便你不配置环境变量,pyhton 3也可以正常运行,当然特殊情况下再配置。
而且安装python3.3的时候,默认会安装pip,方便我们进行开发。

笔者的观点是,技术尽量用最新的,但是手头确实有程序用的python2,所以搜索之下找到了这个解决办法。

根据pep规范,python3借鉴了unix-linux操作系统的模式,在命令行之如果你要运行learning.py,有一下几种方式:

1. py learning.py
2. learning
运行示例

而如果要运行python程序的话,在安装了python2的前提下可以直接运行

py -2 python2.py

再就是用标记也可以
在文件头用#!python2可以指定python 2作为解释器,写#!python3可以指定解释器为python3

利用hang-bang

这样一来就方便了许多,不用再分别配置环境变量,大家只需要同事安装python2和python3,然后利用这种方式就可以愉快的使用python2和python3了。

多版本python下pip的使用
多版本python下pip的使用-知乎问题连接

There is a better way of coexistence/launching of Python 2 and Python 3 on Windows. The Python 3.3 introduced the Python launcher for Windows (see http://www.python.org/dev/peps/pep-0397/).
After installation of Python 3.3, the py.exe
and pyw.exe
is copied to your c:\Windows
directory, and the associations are set for the .py
extension so that it uses the launcher. By default, Python 2 is launched for py script.py
. The py -3 script.py
launches Python 3. (This also means that no path for Python must be added to the environment -- the C:\Windows
already is in the PATH
.)
The best of all is that #!python2
in the script causes lauching via Python 2, the #!python3
causes launching the script via Python 3. This way, you can use scripts for both versions of Python, and you can lauch them the unified way -- py script.py
or by just clicking on the script icon.
There are more details but this is basically what you need.
Update: When using Python launcher for Windows, you can also launch your Python script from cmd
window by typing > script.py
(that is without explicitly typing py
--the name of the Python launcher--in front of the script name) or even by typing the name without the .py
extension (that is just > script
).
This way, things start to resemble the Unix way of naming scripts (without the need for the extension); however, you still have to add the .py
extension when creating the script file.
(Yes, it is a bit more messy than the Unix approach. This is the difference between the "Think first!"and the "Sell first!" approaches of developments of the OSes. Anyway, my kudos to the Python development team to squeeze the best out of the Windows -- by releasing the Python launcher for Windows.)

上一篇下一篇

猜你喜欢

热点阅读