Как переключить python 2 на python 3 windows

I'm trying to find the best way to switch between the two python compilers, 2.7 to 3.3. I ran the python script from the cmd like this: python ex1.py Where do I set the "python" environment in ...

I’m trying to find the best way to switch between the two python compilers, 2.7 to 3.3.
I ran the python script from the cmd like this:

python ex1.py

Where do I set the «python» environment in the window’s environment variable to point to either python 3.3 or 2.7?

I am wondering if there is an easy way to switch between the two versions from the cmd line?

007mrviper's user avatar

asked Aug 5, 2013 at 12:39

JPC's user avatar

0

No need for «tricks». Python 3.3 comes with PyLauncher «py.exe», installs it in the path, and registers it as the «.py» extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:

#!python2
print "hello"

Or

#!python3
print("hello")

From the command line:

py -3 hello.py

Or

py -2 hello.py

py hello.py by itself will choose the latest Python installed, or consult the PY_PYTHON environment variable, e.g. set PY_PYTHON=3.6.

See Python Launcher for Windows

answered Aug 5, 2013 at 13:17

Mark Tolonen's user avatar

Mark TolonenMark Tolonen

160k24 gold badges168 silver badges242 bronze badges

1

For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps —

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

answered Aug 5, 2013 at 12:45

Sukrit Kalra's user avatar

Sukrit KalraSukrit Kalra

32.3k7 gold badges66 silver badges70 bronze badges

3

In case you have both python 2 and 3 in your path, you can move up the Python27 folder in your path, so it search and executes python 2 first.

answered Mar 17, 2019 at 14:33

Philip L's user avatar

Philip LPhilip L

3291 gold badge3 silver badges14 bronze badges

They are 3 ways you can achieve this using the py command (py-launcher) in python 3, virtual environment or configuring your default python system path. For illustration purpose, you may see tutorial https://www.youtube.com/watch?v=ynDlb0n27cw&t=38s

answered May 18, 2017 at 10:35

Timothy Mugayi's user avatar

simply add both to the env variables and then you have to move the version you want to the top

answered Mar 15, 2021 at 12:06

MOHAMMED NABAWY's user avatar

There is an easier way than all of the above; You can use the PY_PYTHON environment variable.
From inside the cmd.exe shell;

For the latest version of Python 2

set PY_PYTHON=2

For the latest version of Python 3

set PY_PYTHON=3

If you want it to be permanent, set it in the control panel. Or use setx instead of set in the cmd.exe shell.

answered Jul 11, 2019 at 20:49

ehambright's user avatar

ehambrightehambright

1,32917 silver badges27 bronze badges

6

Are you using Python version 3+?

  1. Go to your project path
  2. Run py -[version_number_here] and hit Enter
    -> This will open the Python’s Terminal (sort of)

Happy Coding 🤙

answered Dec 20, 2021 at 9:58

Kenn's user avatar

KennKenn

5371 gold badge4 silver badges7 bronze badges

You can try to rename the python executable in the python3 folder to python3, that is if it was named python formally… it worked for me

answered Dec 31, 2016 at 17:16

ahmadore's user avatar

1

Последнее обновление: 16.12.2022

На одной рабочей машине одновременно может быть установлено несколько версий Python. Это бывает полезно, когда идет работа с некоторыми внешними библиотеками, которые поддерживают разные версии python, либо в силу каких-то
других причин нам надо использовать несколько разных версий. Например, на момент написания статьи последней и актуальной является версия Python 3.11.
Но, допустим, необходимо также установить версию 3.10, как в этом случае управлять отдельными версиями Python?

Windows

На странице загрузок https://www.python.org/downloads/ мы можем найти ссылку на нужную версию:

Управление несколькими версиями Python

И также загрузить ее и установить:

Установка разных версий Python на Windows

Чтобы при использовании интерпретатора Python не прописывать к нему весь путь, добавим при установке его в переменные среды. Но здесь надо учитывать, что в переменных среды
может содержаться несколько путей к разным интерпретаторам Python:

Установка разных версий Python на Windows в переменные среды

Та версия Python, которая находится выше, будет версией по умолчанию. С помощью кнопки «Вверх» можно нужную нам версию переместить в начало, сделав версией по умолчанию.
Например, в моем случае это версия 3.11. Соответственно, если я введу в терминале команду

или

то консоль отобразит версию 3.11:

C:python>python --version
Python 3.11.0

Для обращения к версии 3.10 (и всем другим версиям) необходимо использовать указывать номер версии:

C:python>py -3.10 --version
Python 3.10.9

например, выполнение скрипта hello.py с помощью версии 3.10:

Подобным образом можно вызывать и другие версии Python.

MacOS

На MacOS можно установить разные версии, например, загрузив с официального сайта пакет установщика для определенной версии.

Для обращения к определенной версии Python на MacOS указываем явным образом подверсию в формате python3.[номер_подверсии]. Например, у меня установлена версия
Python 3.10. Проверим ее версию:

Аналогично обращении к версии python3.9 (при условии если она установлена)

К примеру выполнение скрипта hello.py с помощью версии python 3.10:

Linux

На Linux также можно установить одновременно несколько версий Python. Например, установка версий 3.10 и 3.11:

sudo apt-get install python3.10
sudo apt-get install python3.11

Одна из версий является версий по умолчанию. И для обращения к ней достаточно прописать python3, например, проверим версию по умолчанию:

Для обращения к другим версиям надо указывать подверсию:

python3.10 --version
python3.11 --version

Например, выполнение скрипта hello с помощью версии Python 3.10:

Но может сложиться ситуация, когда нам надо изменить версию по умолчанию. В этом случае применяется команда update-alternatives для связывания
определенной версии Python с командой python3. Например, мы хотим установить в качестве версии по умолчанию Python 3.11. В этом случае последовательно выполним следующие команды:

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 2

Числа справа указывают на приоритет/состояние. Так, для версии 3.11 указан больший приоритет, поэтому при обращении к python3 будет использоваться именно версия 3.11 (в моем случае это Python 3.11.0rc1)

Управление версиями Python в linux

С помощью команды

sudo update-alternatives --config python3

можно изменить версию по умолчанию

Установка версии Python по умолчанию в linux

I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.

Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I «choose» which version of Python should run it? Will the aforementioned programs be able to handle multiple versions of Python installed at once? I have searched for hours and hours for how to do this to no avail.

Thanks.

Trenton McKinney's user avatar

asked Sep 28, 2010 at 2:40

dln385's user avatar

4

I found that the formal way to do this is as follows:

Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).

Follow the instuctions below, changing the parameters for your needs.

Create the following environment variable (to default on double click):

Name:  PY_PYTHON
Value: 3

To launch a script in a particular interpreter, add the following shebang (beginning of script):

#! python2

To execute a script using a specific interpreter, use the following prompt command:

> py -2 MyScript.py

To launch a specific interpreter:

> py -2

To launch the default interpreter (defined by the PY_PYTHON variable):

> py

Resources

Documentation: Using Python on Windows

PEP 397 — Python launcher for Windows

answered Aug 12, 2013 at 21:48

3

What I did was download both 2.7.6 and 3.3.4. Python 3.3.4 has the option to add the path to it in the environment variable so that was done. So basically I just manually added Python 2.7.6.

How to…

  1. Start > in the search type in environment select «Edit environment variables to your account»1

  2. Scroll down to Path, select path, click edit.

  3. Add C:Python27;
    so you should have paths to both versions of Python there, but if you don’t this you can easily edit it so that you do….. C:Python27;C:Python33;

  4. Navigate to the Python27 folder in C: and rename a copy of python.exe to python2.exe

  5. Navigate to the Python34 folder in C: and rename a copy of python.exe to python3.exe

  6. Test: open up commmand prompt and type python2 ….BOOM! Python 2.7.6. exit out.

  7. Test: open up commmand prompt and type python3 ….BOOM! Python 3.4.3. exit out.

Note: (so as not to break pip commands in step 4 and 5, keep copy of python.exe in the same directory as the renamed file)

Davos's user avatar

Davos

4,85940 silver badges61 bronze badges

answered Mar 25, 2014 at 6:13

user3458330's user avatar

user3458330user3458330

9736 silver badges3 bronze badges

6

I have multiple versions in windows.
I just change the exe name of the version I’m not defaulting to.

python.exe —> python26.exe

pythonw.exe —> pythonw26.exe

As for package installers, most exe installers allow you to choose the python install to add the package too.
For manual installation check out the —prefix option to define where the package should be installed:

http://docs.python.org/install/index.html#alternate-installation-windows-the-prefix-scheme

Community's user avatar

answered Sep 28, 2010 at 3:07

monkut's user avatar

monkutmonkut

41.2k24 gold badges122 silver badges149 bronze badges

3

If you use Anaconda Python, you can easily install various environments.

Say you had Anaconda Python 2.7 installed and you wanted a python 3.4 environment:

conda create -n py34 python=3.4 anaconda

Then to activate the environment:

activate py34

And to deactive:

deactivate py34

(With Linux, you should use source activate py34.)

Links:

Download Anaconda Python

Instructions for environments

answered Oct 16, 2014 at 12:54

philshem's user avatar

philshemphilshem

24.5k7 gold badges60 silver badges126 bronze badges

1

To install and run any version of Python in the same system follow my guide below.


For example say you want to install Python 2.x and Python 3.x on the same Windows system.

  1. Install both of their binary releases anywhere you want.

    • When prompted do not register their file extensions and
    • do not add them automatically to the PATH environment variable
  2. Running simply the command python the executable that is first met in PATH will be chosen for launch. In other words, add the Python directories manually. The one you add first will be selected when you type python. Consecutive python programs (increasing order that their directories are placed in PATH) will be chosen like so:

    • py -2 for the second python
    • py -3 for the third python etc..
  3. No matter the order of «pythons» you can:

    • run Python 2.x scripts using the command: py -2 (Python 3.x functionality) (ie. the first Python 2.x installation program found in your PATH will be selected)
    • run Python 3.x scripts using the command: or py -3 (ie. the first Python 3.x installation program found in your PATH will be selected)

In my example I have Python 2.7.14 installed first and Python 3.5.3. This is how my PATH variable starts with:

PATH=C:Program FilesMicrosoft MPIBin;C:Python27;C:Program FilesPython_3.6Scripts;C:Program FilesPython_3.6;C:ProgramDataOracleJavajavapath;C:Program Files (x86)Common FilesIntelShared

Note that Python 2.7 is first and Python 3.5 second.

  • So running python command will launch python 2.7 (if Python 3.5 the same command would launch Python 3.5).
  • Running py -2 launches Python 2.7 (because it happens that the second Python is Python 3.5 which is incompatible with py -2).
    Running py -3 launches Python 3.5 (because it’s Python 3.x)
  • If you had another python later in your path you would launch like so: py -4. This may change if/when Python version 4 is released.

Now py -4 or py -5 etc. on my system outputs: Requested Python version (4) not installed or Requested Python version (5) not installed etc.

Hopefully this is clear enough.

answered Jan 13, 2018 at 12:00

KeyC0de's user avatar

KeyC0deKeyC0de

4,4788 gold badges43 silver badges64 bronze badges

6

Here’s what you can do:

Install cmder.
Open and use Cmder as you would with you cmd terminal.
Use the command alias to create command aliases.

I did the following:

alias python2 = c:python27python.exe
alias python3 = c:python34python.exe

And that’s it! ;-)

Tonechas's user avatar

Tonechas

13.2k15 gold badges43 silver badges78 bronze badges

answered May 26, 2015 at 17:42

victorwestmann's user avatar

3

I actually just thought of an interesting solution. While Windows will not allow you to easily alias programs, you can instead create renamed batch files that will call the current program.

Instead of renaming the executable which will break a lot of thing including pip, create the file python2.bat in the same directory as the python2.exe. Then add the following line:

%~dp0python %*

What does this archaic syntax mean? Well, it’s a batch script, (Windows version of bash). %~dp0 gets the current directory and %* will just pass all the arguments to python that were passed to the script.

Repeat for python3.bat

You can also do the same for pip and other utilities, just replace the word python in the file with pip or whathever the filename. The alias will be whatever the file is named.

Best of all, when added to the PATH, Windows ignores the extension so running

python3

Will launch the python3 version and and the command python2 will launch the python2 version.

BTW, this is the same technique Spyder uses to add itself to the path on Windows. :)

answered Feb 19, 2016 at 21:37

Skylion's user avatar

SkylionSkylion

2,66624 silver badges49 bronze badges

1

Starting version 3.3 Windows version has Python launcher, please take a look at section 3.4. Python Launcher for Windows

Efren's user avatar

Efren

3,5113 gold badges31 silver badges72 bronze badges

answered Aug 26, 2013 at 12:11

Dmitry Sobolev's user avatar

You can install multiple versions of Python one machine, and during setup, you can choose to have one of them associate itself with Python file extensions. If you install modules, there will be different setup packages for different versions, or you can choose which version you want to target. Since they generally install themselves into the site-packages directory of the interpreter version, there shouldn’t be any conflicts (but I haven’t tested this). To choose which version of python, you would have to manually specify the path to the interpreter if it is not the default one. As far as I know, they would share the same PATH and PYTHONPATH variables, which may be a problem.

Note: I run Windows XP. I have no idea if any of this changes for other versions, but I don’t see any reason that it would.

answered Sep 28, 2010 at 2:46

li.davidm's user avatar

li.davidmli.davidm

11.3k4 gold badges28 silver badges30 bronze badges

1

What I have done on my own windows computer where I have Python 2.7 and Python 3.4 installed is I wrote a simple .bat file in the same directory as my Python.exe files. They look something like,

cmd /k "c:python27python.exe" %*

The %* allows you to add arguments (Python files) afterwards. I believe /k keeps the prompt open after it finishes running the script. Then I save that as python27.bat Then I go to my Python 3 directory and make a bat file there. Now in my command line I can write

Python27 helloworld.py

Or

Python34 helloworld.py

And they will run in their respective versions of Python. Make sure that c:python27 and c:python34 are in your environment variables.

I got my answer from here

answered Jul 6, 2016 at 9:45

Bryan Kimani's user avatar

I did this in three steps by following the instructions here: This is all taken directly from here: http://ipython.readthedocs.io/en/stable/install/kernel_install.html. I’m currently running Python 2.x on Windows 8 and have Anaconda 4.2.13 installed.

1) First install the latest version of python:

conda create -n python3 python=3 ipykernel

2) Next activate python3

activate python3

3) Install the kernel:

python -m ipykernel install --user

If you have Python 3 installed and want to install 2, switch the 2 and the 3 above. When you open a new notebook, you can now choose between Python 2 or 3.

answered Jan 25, 2017 at 6:06

Moiz Kapadia's user avatar

Check your system environment variables after installing Python, python 3’s directories should be first in your PATH variable, then python 2.

Whichever path variable matches first is the one Windows uses.

As always py -2 will launch python2 in this scenario.

answered Nov 4, 2015 at 16:44

Spitfire19's user avatar

Spitfire19Spitfire19

2381 gold badge2 silver badges10 bronze badges

I have encountered that problem myself and I made my launchers in a .bat so you could choose the version you want to launch.

The only problem is your .py must be in the python folder, but anyway here is the code:

For Python2

@echo off
title Python2 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 23, 24, 25, 26)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
path = %PATH%;C:Python%version%
cd C:Python%version%
python %launch%.py
pause

For Python3

@echo off
title Python3 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 31, 32, 33, 34)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
cls
set path = %PATH%:C:Python%version%
cd C:Python%version%
python %launch%.py
pause

Save them as .bat and follow the instructions inside.

Tonechas's user avatar

Tonechas

13.2k15 gold badges43 silver badges78 bronze badges

answered Aug 1, 2014 at 16:08

KinDa's user avatar

KinDaKinDa

211 silver badge4 bronze badges

Install the one you use most (3.3 in my case) over the top of the other. That’ll force IDLE to use the one you want.

Alternatively (from the python3.3 README):

Installing multiple versions

On Unix and Mac systems if you intend to install multiple versions of Python
using the same installation prefix (—prefix argument to the configure script)
you must take care that your primary python executable is not overwritten by the
installation of a different version. All files and directories installed using
«make altinstall» contain the major and minor version and can thus live
side-by-side. «make install» also creates ${prefix}/bin/python3 which refers to
${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the
same prefix you must decide which version (if any) is your «primary» version.
Install that version using «make install». Install all other versions using
«make altinstall».

For example, if you want to install Python 2.6, 2.7 and 3.3 with 2.7 being the
primary version, you would execute «make install» in your 2.7 build directory
and «make altinstall» in the others.

answered Jul 15, 2013 at 17:43

abudhabikid's user avatar

I just had to install them. Then I used the free (and portable) soft at http://defaultprogramseditor.com/ under «File type settings»/»Context menu»/search:»py», chose .py file and added an ‘open’ command for the 2 IDLE by copying the existant command named ‘open with IDLE, changing names to IDLE 3.4.1/2.7.8, and remplacing the files numbers of their respective versions in the program path. Now I have just to right click the .py file and chose which IDLE I want to use. Can do the same with direct interpreters if you prefer.

answered Jul 13, 2014 at 23:02

wheya's user avatar

I use a simple solution to switch from a version to another version of python, you can install all version you want. All you have to do is creating some variable environment.
In my case, I have installed python 2.7 and python 3.8.1, so I have created this environment variables:

PYTHON_HOME_2.7=<path_python_2.7>
PYTHON_HOME_3.8.1=<path_python_3.8.1>
PYTHON_HOME=%PYTHON_HOME_2.7%

then in my PATH environment variable I put only %PYTHON_HOME% and %PYTHON_HOME%Scripts. In the example above I’m using the version 2.7, when I want to switch to the other version I have only to set the PYTHON_HOME=%PYTHON_HOME_3.8.1%.
I use this method to switch quickly from a version to another also for JAVA, MAVEN, GRADLE,ANT, and so on.

answered Oct 28, 2020 at 17:10

walthor's user avatar

Only Works if your running your code in your Python IDE

I have both Python 2.7 and Python 3.3 installed on my windows operating system. If I try to launch a file, it will usually open up on the python 2.7 IDE. How I solved this issue, was when I choose to run my code on python 3.3, I open up python 3.3 IDLE(Python GUI), select file, open my file with the IDLE and save it. Then when I run my code, it runs to the IDLE that I currently opened it with. It works vice versa with 2.7.

Alexandre Bell's user avatar

answered Feb 11, 2014 at 2:53

user3295433's user avatar

I have installed both python 2.7.13 and python 3.6.1 on windows 10pro and I was getting the same «Fatal error» when I tried pip2 or pip3.

What I did to correct this was to go to the location of python.exe for python 2 and python 3 files and create a copy of each, I then renamed each copy to python2.exe and python3.exe depending on the python version in the installation folder. I therefore had in each python installation folder both a python.exe file and a python2.exe or python3.exe depending on the python version.

This resolved my problem when I typed either pip2 or pip3.

Sergio Ayestarán's user avatar

answered Apr 1, 2017 at 17:44

eddy onyango's user avatar

If you can’t get anything else to work, open an interpreter in whichever version you choose (I prefer using iPython) and:

import subprocess

subprocess.call('python script.py -flags')

This uses whichever python version you are currently operating under. Works fine for a single script, but will quickly get out of hand if there are lots of scripts you run, in which case you can always make a batch file with all of these calls inside. Not the most elegant answer, but it works.

Is there a way to make aliases for different python version a la Linux?

Alex P.'s user avatar

Alex P.

29.8k17 gold badges118 silver badges168 bronze badges

answered Feb 13, 2014 at 16:01

user2796022's user avatar

I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.

Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I «choose» which version of Python should run it? Will the aforementioned programs be able to handle multiple versions of Python installed at once? I have searched for hours and hours for how to do this to no avail.

Thanks.

Trenton McKinney's user avatar

asked Sep 28, 2010 at 2:40

dln385's user avatar

4

I found that the formal way to do this is as follows:

Just install two (or more, using their installers) versions of Python on Windows 7 (for me work with 3.3 and 2.7).

Follow the instuctions below, changing the parameters for your needs.

Create the following environment variable (to default on double click):

Name:  PY_PYTHON
Value: 3

To launch a script in a particular interpreter, add the following shebang (beginning of script):

#! python2

To execute a script using a specific interpreter, use the following prompt command:

> py -2 MyScript.py

To launch a specific interpreter:

> py -2

To launch the default interpreter (defined by the PY_PYTHON variable):

> py

Resources

Documentation: Using Python on Windows

PEP 397 — Python launcher for Windows

answered Aug 12, 2013 at 21:48

3

What I did was download both 2.7.6 and 3.3.4. Python 3.3.4 has the option to add the path to it in the environment variable so that was done. So basically I just manually added Python 2.7.6.

How to…

  1. Start > in the search type in environment select «Edit environment variables to your account»1

  2. Scroll down to Path, select path, click edit.

  3. Add C:Python27;
    so you should have paths to both versions of Python there, but if you don’t this you can easily edit it so that you do….. C:Python27;C:Python33;

  4. Navigate to the Python27 folder in C: and rename a copy of python.exe to python2.exe

  5. Navigate to the Python34 folder in C: and rename a copy of python.exe to python3.exe

  6. Test: open up commmand prompt and type python2 ….BOOM! Python 2.7.6. exit out.

  7. Test: open up commmand prompt and type python3 ….BOOM! Python 3.4.3. exit out.

Note: (so as not to break pip commands in step 4 and 5, keep copy of python.exe in the same directory as the renamed file)

Davos's user avatar

Davos

4,85940 silver badges61 bronze badges

answered Mar 25, 2014 at 6:13

user3458330's user avatar

user3458330user3458330

9736 silver badges3 bronze badges

6

I have multiple versions in windows.
I just change the exe name of the version I’m not defaulting to.

python.exe —> python26.exe

pythonw.exe —> pythonw26.exe

As for package installers, most exe installers allow you to choose the python install to add the package too.
For manual installation check out the —prefix option to define where the package should be installed:

http://docs.python.org/install/index.html#alternate-installation-windows-the-prefix-scheme

Community's user avatar

answered Sep 28, 2010 at 3:07

monkut's user avatar

monkutmonkut

41.2k24 gold badges122 silver badges149 bronze badges

3

If you use Anaconda Python, you can easily install various environments.

Say you had Anaconda Python 2.7 installed and you wanted a python 3.4 environment:

conda create -n py34 python=3.4 anaconda

Then to activate the environment:

activate py34

And to deactive:

deactivate py34

(With Linux, you should use source activate py34.)

Links:

Download Anaconda Python

Instructions for environments

answered Oct 16, 2014 at 12:54

philshem's user avatar

philshemphilshem

24.5k7 gold badges60 silver badges126 bronze badges

1

To install and run any version of Python in the same system follow my guide below.


For example say you want to install Python 2.x and Python 3.x on the same Windows system.

  1. Install both of their binary releases anywhere you want.

    • When prompted do not register their file extensions and
    • do not add them automatically to the PATH environment variable
  2. Running simply the command python the executable that is first met in PATH will be chosen for launch. In other words, add the Python directories manually. The one you add first will be selected when you type python. Consecutive python programs (increasing order that their directories are placed in PATH) will be chosen like so:

    • py -2 for the second python
    • py -3 for the third python etc..
  3. No matter the order of «pythons» you can:

    • run Python 2.x scripts using the command: py -2 (Python 3.x functionality) (ie. the first Python 2.x installation program found in your PATH will be selected)
    • run Python 3.x scripts using the command: or py -3 (ie. the first Python 3.x installation program found in your PATH will be selected)

In my example I have Python 2.7.14 installed first and Python 3.5.3. This is how my PATH variable starts with:

PATH=C:Program FilesMicrosoft MPIBin;C:Python27;C:Program FilesPython_3.6Scripts;C:Program FilesPython_3.6;C:ProgramDataOracleJavajavapath;C:Program Files (x86)Common FilesIntelShared

Note that Python 2.7 is first and Python 3.5 second.

  • So running python command will launch python 2.7 (if Python 3.5 the same command would launch Python 3.5).
  • Running py -2 launches Python 2.7 (because it happens that the second Python is Python 3.5 which is incompatible with py -2).
    Running py -3 launches Python 3.5 (because it’s Python 3.x)
  • If you had another python later in your path you would launch like so: py -4. This may change if/when Python version 4 is released.

Now py -4 or py -5 etc. on my system outputs: Requested Python version (4) not installed or Requested Python version (5) not installed etc.

Hopefully this is clear enough.

answered Jan 13, 2018 at 12:00

KeyC0de's user avatar

KeyC0deKeyC0de

4,4788 gold badges43 silver badges64 bronze badges

6

Here’s what you can do:

Install cmder.
Open and use Cmder as you would with you cmd terminal.
Use the command alias to create command aliases.

I did the following:

alias python2 = c:python27python.exe
alias python3 = c:python34python.exe

And that’s it! ;-)

Tonechas's user avatar

Tonechas

13.2k15 gold badges43 silver badges78 bronze badges

answered May 26, 2015 at 17:42

victorwestmann's user avatar

3

I actually just thought of an interesting solution. While Windows will not allow you to easily alias programs, you can instead create renamed batch files that will call the current program.

Instead of renaming the executable which will break a lot of thing including pip, create the file python2.bat in the same directory as the python2.exe. Then add the following line:

%~dp0python %*

What does this archaic syntax mean? Well, it’s a batch script, (Windows version of bash). %~dp0 gets the current directory and %* will just pass all the arguments to python that were passed to the script.

Repeat for python3.bat

You can also do the same for pip and other utilities, just replace the word python in the file with pip or whathever the filename. The alias will be whatever the file is named.

Best of all, when added to the PATH, Windows ignores the extension so running

python3

Will launch the python3 version and and the command python2 will launch the python2 version.

BTW, this is the same technique Spyder uses to add itself to the path on Windows. :)

answered Feb 19, 2016 at 21:37

Skylion's user avatar

SkylionSkylion

2,66624 silver badges49 bronze badges

1

Starting version 3.3 Windows version has Python launcher, please take a look at section 3.4. Python Launcher for Windows

Efren's user avatar

Efren

3,5113 gold badges31 silver badges72 bronze badges

answered Aug 26, 2013 at 12:11

Dmitry Sobolev's user avatar

You can install multiple versions of Python one machine, and during setup, you can choose to have one of them associate itself with Python file extensions. If you install modules, there will be different setup packages for different versions, or you can choose which version you want to target. Since they generally install themselves into the site-packages directory of the interpreter version, there shouldn’t be any conflicts (but I haven’t tested this). To choose which version of python, you would have to manually specify the path to the interpreter if it is not the default one. As far as I know, they would share the same PATH and PYTHONPATH variables, which may be a problem.

Note: I run Windows XP. I have no idea if any of this changes for other versions, but I don’t see any reason that it would.

answered Sep 28, 2010 at 2:46

li.davidm's user avatar

li.davidmli.davidm

11.3k4 gold badges28 silver badges30 bronze badges

1

What I have done on my own windows computer where I have Python 2.7 and Python 3.4 installed is I wrote a simple .bat file in the same directory as my Python.exe files. They look something like,

cmd /k "c:python27python.exe" %*

The %* allows you to add arguments (Python files) afterwards. I believe /k keeps the prompt open after it finishes running the script. Then I save that as python27.bat Then I go to my Python 3 directory and make a bat file there. Now in my command line I can write

Python27 helloworld.py

Or

Python34 helloworld.py

And they will run in their respective versions of Python. Make sure that c:python27 and c:python34 are in your environment variables.

I got my answer from here

answered Jul 6, 2016 at 9:45

Bryan Kimani's user avatar

I did this in three steps by following the instructions here: This is all taken directly from here: http://ipython.readthedocs.io/en/stable/install/kernel_install.html. I’m currently running Python 2.x on Windows 8 and have Anaconda 4.2.13 installed.

1) First install the latest version of python:

conda create -n python3 python=3 ipykernel

2) Next activate python3

activate python3

3) Install the kernel:

python -m ipykernel install --user

If you have Python 3 installed and want to install 2, switch the 2 and the 3 above. When you open a new notebook, you can now choose between Python 2 or 3.

answered Jan 25, 2017 at 6:06

Moiz Kapadia's user avatar

Check your system environment variables after installing Python, python 3’s directories should be first in your PATH variable, then python 2.

Whichever path variable matches first is the one Windows uses.

As always py -2 will launch python2 in this scenario.

answered Nov 4, 2015 at 16:44

Spitfire19's user avatar

Spitfire19Spitfire19

2381 gold badge2 silver badges10 bronze badges

I have encountered that problem myself and I made my launchers in a .bat so you could choose the version you want to launch.

The only problem is your .py must be in the python folder, but anyway here is the code:

For Python2

@echo off
title Python2 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 23, 24, 25, 26)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
path = %PATH%;C:Python%version%
cd C:Python%version%
python %launch%.py
pause

For Python3

@echo off
title Python3 Launcher by KinDa
cls
echo Type the exact version of Python you use (eg. 31, 32, 33, 34)
set/p version=
cls
echo Type the file you want to launch without .py (eg. hello world, calculator)
set/p launch=
cls
set path = %PATH%:C:Python%version%
cd C:Python%version%
python %launch%.py
pause

Save them as .bat and follow the instructions inside.

Tonechas's user avatar

Tonechas

13.2k15 gold badges43 silver badges78 bronze badges

answered Aug 1, 2014 at 16:08

KinDa's user avatar

KinDaKinDa

211 silver badge4 bronze badges

Install the one you use most (3.3 in my case) over the top of the other. That’ll force IDLE to use the one you want.

Alternatively (from the python3.3 README):

Installing multiple versions

On Unix and Mac systems if you intend to install multiple versions of Python
using the same installation prefix (—prefix argument to the configure script)
you must take care that your primary python executable is not overwritten by the
installation of a different version. All files and directories installed using
«make altinstall» contain the major and minor version and can thus live
side-by-side. «make install» also creates ${prefix}/bin/python3 which refers to
${prefix}/bin/pythonX.Y. If you intend to install multiple versions using the
same prefix you must decide which version (if any) is your «primary» version.
Install that version using «make install». Install all other versions using
«make altinstall».

For example, if you want to install Python 2.6, 2.7 and 3.3 with 2.7 being the
primary version, you would execute «make install» in your 2.7 build directory
and «make altinstall» in the others.

answered Jul 15, 2013 at 17:43

abudhabikid's user avatar

I just had to install them. Then I used the free (and portable) soft at http://defaultprogramseditor.com/ under «File type settings»/»Context menu»/search:»py», chose .py file and added an ‘open’ command for the 2 IDLE by copying the existant command named ‘open with IDLE, changing names to IDLE 3.4.1/2.7.8, and remplacing the files numbers of their respective versions in the program path. Now I have just to right click the .py file and chose which IDLE I want to use. Can do the same with direct interpreters if you prefer.

answered Jul 13, 2014 at 23:02

wheya's user avatar

I use a simple solution to switch from a version to another version of python, you can install all version you want. All you have to do is creating some variable environment.
In my case, I have installed python 2.7 and python 3.8.1, so I have created this environment variables:

PYTHON_HOME_2.7=<path_python_2.7>
PYTHON_HOME_3.8.1=<path_python_3.8.1>
PYTHON_HOME=%PYTHON_HOME_2.7%

then in my PATH environment variable I put only %PYTHON_HOME% and %PYTHON_HOME%Scripts. In the example above I’m using the version 2.7, when I want to switch to the other version I have only to set the PYTHON_HOME=%PYTHON_HOME_3.8.1%.
I use this method to switch quickly from a version to another also for JAVA, MAVEN, GRADLE,ANT, and so on.

answered Oct 28, 2020 at 17:10

walthor's user avatar

Only Works if your running your code in your Python IDE

I have both Python 2.7 and Python 3.3 installed on my windows operating system. If I try to launch a file, it will usually open up on the python 2.7 IDE. How I solved this issue, was when I choose to run my code on python 3.3, I open up python 3.3 IDLE(Python GUI), select file, open my file with the IDLE and save it. Then when I run my code, it runs to the IDLE that I currently opened it with. It works vice versa with 2.7.

Alexandre Bell's user avatar

answered Feb 11, 2014 at 2:53

user3295433's user avatar

I have installed both python 2.7.13 and python 3.6.1 on windows 10pro and I was getting the same «Fatal error» when I tried pip2 or pip3.

What I did to correct this was to go to the location of python.exe for python 2 and python 3 files and create a copy of each, I then renamed each copy to python2.exe and python3.exe depending on the python version in the installation folder. I therefore had in each python installation folder both a python.exe file and a python2.exe or python3.exe depending on the python version.

This resolved my problem when I typed either pip2 or pip3.

Sergio Ayestarán's user avatar

answered Apr 1, 2017 at 17:44

eddy onyango's user avatar

If you can’t get anything else to work, open an interpreter in whichever version you choose (I prefer using iPython) and:

import subprocess

subprocess.call('python script.py -flags')

This uses whichever python version you are currently operating under. Works fine for a single script, but will quickly get out of hand if there are lots of scripts you run, in which case you can always make a batch file with all of these calls inside. Not the most elegant answer, but it works.

Is there a way to make aliases for different python version a la Linux?

Alex P.'s user avatar

Alex P.

29.8k17 gold badges118 silver badges168 bronze badges

answered Feb 13, 2014 at 16:01

user2796022's user avatar

Они устанавливаются отдельно и не конфликтуют. Переключатся можешь в ide. В терминале можешь писать python это версия 2 или python 3 это 3я версия. Качай https://www.python.org и не выдумывай). Конфликт может быть между версиями django и всяких библиотек на этот случай есть https://virtualenv.pypa.io/en/stable/ или docker.

устанавливаются в разные папки, запускаешь просто из каждой свой python.exe и всё, а если вопрос про переменные PATH, то можешь вручную назвать их python2 и python3 и прописать для каждой свой путь

Господа, а вы разве не знаете про консольную команду py? Если вызвать ее py -2 <имя питоновского файла>, то вызовется второй питон, если py -3 — третий. Без параметров, тот, что указан в environment переменной PY_PYTHON. Там еще много опций — у меня на работе все четыре питона стоят, 2.7.13 32.64 бита и 3.6.0 тоже в двух экземплярах.

В большинстве операционных систем Python предустановлен
(ну, кроме Windows, но даже там теперь есть
команда python, которая предложит установить интерпретатор из магазина приложений).
В Unix-подобных операционных системах, таких как Linux и MacOS, Python
пустил корни очень глубоко. Множество компонентов ОС рассчитывают, что Python
установлен и работает стабильно. Это и хорошо, и плохо.

Это хорошо, потому что хотя бы какой-то Python в большинстве систем доступен из
коробки — бери и пользуйся. Иногда доступно сразу несколько версий
интерпретатора, например, python2 указывает на устаревшую версию 2.7,
python3 — на какую-нибудь стабильную версию Python 3, типа 3.6 или 3.7, а
просто python указывает либо на одно, либо на другое (в последнее время
предпочтение чаще отдаётся третьей версии). Для обучения или для
тестирования этого может быть вполне достаточно.

С другой стороны, это плохо, потому что, как правило, предустановленный Python
настолько стабилен, что уже успел зарасти мхом.
В некоторых системах до сих пор предустановлен только Python 2,
но даже если вам повезёт получить Python третьей версии,
то наверняка он будет отставать от последней версии на пару минорных релизов.
Не факт, что вам это подойдёт.

Иногда нужно иметь сразу несколько версий Python для работы над
разными проектами, например, 3.7 и 3.8. В некоторых ОС нужные версии можно
установить через пакетный менеджер (например, в Fedora через dnf)
— из основных репозиториев или из сторонних.
Но зачастую такие репозитории содержат не все релизы
интерпретаторов, а лишь выбранное мейнтейнерами репозиториев подмножество.

Решение у всех этих проблем одно — нужно установить недостающие версии
интерпретатора, какими бы они ни были. Этому и посвящён пост.

pyenv — утилита, которая позволяет
легко переключаться между несколькими версиями интерпретатора Python, а
также устанавливать новые. Позволяет устанавливать, наверное, вообще
все известные науке версии интерпретаторов Python. Работает просто и незаметно.

pyenv — это всего лишь один из последователей аналогичного инструмента
из мира Ruby — rbenv.
Есть ещё и nodenv для Node.js,
который тоже вдохновился rbenv.

Проект написан целиком на bash. Это значит, что он никак не зависит
от Python — было бы забавно, если бы для установки Python нужен был бы Python.
Также это означает, что на Windows pyenv работать не будет
(тред с обсуждением).
Следует отметить, что в Windows проблема установки нескольких версий
и не возникает — там всегда можно скачать и установить
сколько угодно интерпретаторов с официального сайта,
а pylauncher поможет выбрать
из них нужную версию.
Кроме того, пользователи современных версий
Windows могут использовать pyenv внутри WSL (Windows Subsystem for Linux).
Ещё это означает, что у авторов много отваги — я бы не решился писать
на bash что-то настолько сложное. Как же хорошо, что всё уже написано.

Установка

  1. Скачаем pyenv.

    Установка pyenv производится простым клонированием git-репозитория.

    У проекта есть умный скрипт,
    который скачает pyenv и его сотоварищей:

    $ curl https://pyenv.run | bash
    

    Скрипт не требует прав суперпользователя (без sudo), потому что
    всё устанавливается в домашнюю директорию пользователя. Туда же
    будут устанавливаться и интерпретаторы. Если страшно запускать
    какие-то скрипты из интернета (так и должно быть), то прочитать код скрипта можно
    здесь.

  2. Настроим шелл.

    Предыдущая команда перед завершением должна была напечатать инструкции
    по настройке шелла. Допустим, в случае с bash она выводит
    следующее:

    WARNING: seems you still have not added 'pyenv' to the load path.
    
    # Load pyenv automatically by adding
    # the following to ~/.bashrc:
    
    export PATH="~/.pyenv/bin:$PATH"
    eval "$(pyenv init -)"
    eval "$(pyenv virtualenv-init -)"
    

    В случае с zsh нужно будет добавить те же самые строки в ~/.zshrc.

    В случае с fish в связи с особенностями самого шелла инструкции отличаются:

    # Load pyenv automatically by adding
    # the following to ~/.config/fish/config.fish:
    
    set -x PATH "~/.pyenv/bin" $PATH
    status --is-interactive; and . (pyenv init -|psub)
    status --is-interactive; and . (pyenv virtualenv-init -|psub)
    

    Кстати, горячо рекомендую попробовать fish, очень удобный шелл.

  3. Установим зависимости для сборки.

    При установке новой версии интерпретатора через pyenv под капотом
    происходит сборка из исходников, поэтому для успешной установки
    необходимы некоторые зависимости. Полный и актуальный список
    для своей ОС смотрите здесь
    или здесь.
    Лучше установить всё заранее.

  4. Перезапустим шелл и проверим установку.

    $ pyenv --version
    pyenv 1.2.18
    

Как это работает

pyenv работает благодаря манипуляциям над переменной окружения $PATH.
Эта переменная содержит в себе список директорий, в которых ОС будет искать
исполняемые файлы, вызванные без указания полного пути. Именно
благодаря этой переменной мы можем в терминале вместо /bin/cat вызывать
просто cat. Когда мы набираем в терминале имя программы (cat),
ОС перебирает директории из $PATH слева направо, пока в одной
из них (в данном примере /bin) не найдёт программу с именем cat,
которую и запустит. Поиск прекращается после первого совпадения.

Команда pyenv init -, которую мы добавили в конфиг шелла (.bashrc или аналог)
добавляет директории pyenv в самое начало переменной $PATH.
Зачем это нужно? pyenv создаёт небольшие исполняемые файлы,
так называемые файлы-прослойки (shims), для всех команд,
которыми он собирается управлять, например, python, pip, ipython и так далее.
Эти файлы-прослойки должны попасть в $PATH прежде самих управляемых программ
и «затенить» системные python, pip и так далее.
Эти файлы-прослойки в конечном счёте просто вызывают сам pyenv
с нужными аргументами.
Таким образом pyenv перехватывает обращения к некоторым именам,
и анализируя поступившую к нему информацию,
принимает решение о том, какую именно версию Python нужно запустить.
При выборе версии pyenv принимает во внимание следующие факторы в
указанном порядке:

  1. Переменная окружения PYENV_VERSION, если указана.

    В неё можно указать какую конкретно версию Python нужно использовать
    в рамках текущего сеанса. Удобно, если вам по какой-то причине понадобится
    сменить выбранную версию интерпретатора, например, в одном
    из окон терминала.

  2. Локальная версия Python.

    При помощи специального файла .python-version можно настроить
    версию интерпретатора для определенного проекта. Захо́дите внутрь
    директории (cd project/), и pyenv внезапно понимает, что нужно
    сменить Python. Выхо́дите обратно — версия Python меняется на глобальную.
    Это распространяется и на все поддиректории проекта —
    pyenv рекурсивно ищет файл .python-version вверх по файловой системе,
    пока не дойдёт до корня.

  3. Глобальная версия Python.

    В файле ~/.pyenv/version записана глобальная версия Python, которая
    будет использоваться по умолчанию, если не сконфигурирована локальная
    версия.

Вам вряд ли придётся вручную трогать эти файлы, потому что у pyenv есть
удобные команды (pyenv local и pyenv global),
чтобы ими управлять, но знать о файлах всё равно полезно.

Использование

Установка новой версии Python

Сначала посмотрим, какие версии Python pyenv может установить:

$ pyenv install --list
...
3.6.0
3.6-dev
3.6.1
3.6.2
3.6.3
3.6.4
3.6.5
3.6.6
3.6.7
3.6.8
3.6.9
3.6.10
3.7.0
3.7-dev
3.7.1
3.7.2
3.7.3
3.7.4
3.7.5
3.7.6
3.7.7
3.8.0
3.8-dev
3.8.1
3.8.2
3.9.0a6
3.9-dev
...

Список довольно длинный, поэтому я его подсократил. Обычно вас будут
интересовать такие версии, как 3.8.2 или 3.7.7 — это версии самой
распространённой реализации интерпретатора CPython. Но если
вам нужна экзотика, то pyenv умеет устанавливать любые сорта интерпретаторов
Python (pypy3.6-7.3.0, stackless-3.7.5, jython-2.7.1,
ironpython-2.7.7, micropython-1.12 и т.д.). Для вас ведь не стало
новостью, что существует много разных реализаций интерпретатора Python?

Установим CPython 3.8.2:

$ pyenv install 3.8.2
Downloading Python-3.8.2.tar.xz...
Installing Python-3.8.2...

Через пару минут ожидания ваш новоиспечённый Python будет готов.

Можно сразу же назначить эту версию глобальной:

$ pyenv global 3.8.2
$ python -V
Python 3.8.2

Давайте в целях демонстрации установим ещё парочку интерпретаторов:

$ pyenv install 2.7.18
$ pyenv install 3.9.0a6

Получим список установленных версий интерпретатора:

$ pyenv versions
  2.7.18
* 3.8.2 (set by /home/br0ke/.pyenv/version)
  3.9.0a6

Кстати, если нужно, то можно делать активными сразу несколько
версий одновременно:

$ pyenv global 3.8.2 2.7.18

Теперь вывод версий покажет следующее:

$ pyenv versions
* 2.7.18 (set by /home/br0ke/.pyenv/version)
* 3.8.2 (set by /home/br0ke/.pyenv/version)
  3.9.0a6

А работать это будет вот таким образом:

$ python -V
Python 3.8.2
$ python3 -V
Python 3.8.2
$ python2 -V
Python 2.7.18

Грубо говоря, та версия, которая указана первой (3.8.2),
имеет приоритет и занимает все нужные ей имена. Следующие версии (2.7.18)
могут занять любые оставшиеся свободные имена (в данном случае, это только имя
python2).

А файл глобальной версии ~/.pyenv/version на данный момент имеет вот
такое содержимое:

$ cat ~/.pyenv/version
3.8.2
2.7.18

Локальная версия

Давайте создадим директорию и войдём в неё:

$ mkdir my_project
$ cd my_project

Представим, что в этой директории мы будем разрабатывать некий
проект, на котором мы хотим опробовать фишки нового Python 3.9.
Сообщим об этом pyenv:

В директории появился файл .python-version со следующим содержимым:

$ cat .python-version
3.9.0a6

На данный момент список версий показывает следующее (удобно использовать
эту команду, чтобы понять какую версию и почему pyenv активирует):

$ pyenv versions
  2.7.18
  3.8.2
* 3.9.0a6 (set by /home/br0ke/my_project/.python-version)

Изменения немедленно вступили в силу:

$ python -V
Python 3.9.0a6

Но эта конфигурация никак не влияет на работу pyenv вне директории проекта:

$ cd ..
$ python -V
3.8.2

Как и в случае с глобальной конфигурацией, можно локально активировать
сразу несколько версий интерпретатора.

Установим IPython

Часто бывает нужно установить какой-нибудь пакет так, чтобы он тоже
стал доступен из командной строки. Допустим, что нам нужно установить
ipython — более удобную версию REPL Python.
Сделаем это:

$ cd my_project
$ pip install ipython

Запустим:

$ ipython
Python 3.9.0a6 (default, May  3 2020, 16:58:20)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.14.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

Программа сразу доступна, благодаря тому, что pyenv очень умный и
создал новый файл-прослойку (shim) автоматически:

$ which ipython
/home/br0ke/.pyenv/shims/ipython

Вне директории с проектом ipython будет недоступен, ведь он же установлен
в локальный интерпретатор 3.9.0a6, а снаружи активирован другой
интерпретатор — можете проверить самостоятельно.

Возникают ситуации, когда по какой-то причине прослойка не создалась
или с ней случилось что-то ещё, например, удалилась:

$ rm $(which ipython)
$ ipython
No such file or directory

Не беда! Можно попросить pyenv пересоздать их все заново:

И всё работает снова:

$ ipython
Python 3.9.0a6 (default, May  3 2020, 16:58:20)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.14.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

Можно вообще добавить команду pyenv rehash в свой ~/.bashrc (или аналог),
чтобы при запуске шелла гарантированно иметь рабочие файлы-прослойки (shims).

Заключение

pyenv — очень удобный и полезный инструмент в ситуациях, когда нужную вам
версию Python нельзя установить средствами операционной системы.
Я вообще предпочитаю устанавливать все нужные мне версии интерпретатора
самостоятельно через pyenv или asdf, даже если ОС уже содержит точно
такую же версию — пусть ОС использует свою копию для служебных целей,
а я для разработки буду использовать свою собственную копию, где смогу
проводить любые кровавые эксперименты, не боясь поломать ОС.

Обязательно
подпишитесь на уведомления
о новых постах в блоге, чтобы ничего не пропустить!

Дополнительное чтение

  • Репозиторий проекта на GitHub;
  • Туториал на RealPython;
  • Альтернатива: универсальный менеджер версий asdf.

Обложка: Schwoaze, Snakes Black Snakes Animal Free Photo

Стандартно рекомендуется использовать команду python3 или python3. 7, чтобы выбрать конкретную версию. Программа запуска py.exe автоматически выберет самую последнюю версию Python, которую вы установили. Вы также можете использовать такие команды, как py -3.7, чтобы выбрать конкретную версию, или py –list, чтобы увидеть, какие версии можно использовать.

Установите предпочитаемую версию по умолчанию с помощью установка переменной окружения PY_PYTHON (например, PY_PYTHON = 3.7). Вы можете узнать, какая версия python используется по умолчанию, набрав py. Вы также можете установить PY_PYTHON3 или PY_PYTHON2, чтобы указать версии Python 3 и Python 2 по умолчанию (если у вас их несколько).

Как запустить определенную версию Python в Windows?

На интерпретатор Python по умолчанию ссылаются в Windows с помощью команда py. Используя командную строку, вы можете использовать параметр -V, чтобы распечатать версию. Вы также можете указать версию Python, которую хотите запустить. Для Windows вы можете просто указать параметр вроде -2.7 для запуска версии 2.7.

Какая версия Python подходит для Windows?

Согласно официальным отчетам документации Python, Питон 3.9. 0. не может использоваться в Windows 7 или более ранней версии Windows. Таким образом, версия до 3.9 будет поддерживаться Windows 7.

Как мне перейти на python3 в Windows?

7 ответы

  1. Щелкните правой кнопкой мыши «Мой компьютер» и выберите «Свойства».
  2. Зайдите в Advanced System Settings.
  3. Щелкните Переменные среды, отредактируйте PATH и добавьте путь к каталогу установки Python 3.

Могу ли я установить 2 версии Python?

Если вы хотите использовать несколько версий Python на одном компьютере, тогда Pyenv — широко используемый инструмент для установки и переключения между версиями. Это не следует путать с ранее упомянутым устаревшим скриптом pyvenv. Он не входит в комплект Python и должен устанавливаться отдельно.

Почему Python не распознается в CMD?

Ошибка «Python не распознается как внутренняя или внешняя команда» обнаружена в командной строке Windows. Ошибка возникает, когда исполняемый файл Python не найден в переменной среды в результате выполнения Python в командной строке Windows.

Как узнать, какая версия Python установлена?

Проверить версию Python из командной строки / в скрипте

  1. Проверьте версию Python в командной строке: –version, -V, -VV.
  2. Проверьте версию Python в скрипте: sys, platform. Различные информационные строки, включая номер версии: sys.version. Кортеж номеров версий: sys.version_info.

Как открыть конкретную версию Python?

Перейдите к C: Python35, чтобы переименовать python.exe в python3.exe, также в C: Python27, переименуйте python.exe в python2.exe. перезапустите командное окно. тип python2 имя_скрипта.py или python3 scriptname.py в командной строке, чтобы переключить версию, которая вам нравится.

Какая версия Python лучше?

Ради совместимости со сторонними модулями всегда безопаснее выбирать версию Python, которая на один важный момент отстает от текущей. На момент написания этой статьи Питон 3.8. 1 это самая последняя версия. Таким образом, безопасный вариант — использовать последнее обновление Python 3.7 (в данном случае Python 3.7.

На каком языке Python?

Python — это интерпретируемый, объектно-ориентированный язык программирования высокого уровня с динамической семантикой.

Python бесплатный?

Открытый исходный код. Python разработан под лицензией с открытым исходным кодом, одобренной OSI, что делает его свободно используемым и распространяемым даже для коммерческого использования. Лицензия Python находится в ведении Python Software Foundation.

Могу ли я запустить Python 3 вместо двух окон?

Итак, чтобы иметь возможность использовать несколько версий Python:

  1. установить Python 2. x (x — любая нужная вам версия)
  2. установите Python 3. x (x — это любая версия, которая вам нужна, также у вас должна быть одна версия 3. x> = 3.3)
  3. откройте командную строку.
  4. типа ру -2. x для запуска Python 2. x.
  5. типа ру -3. x для запуска Python 3. x.

Как переключаться между средами Python?

Переключение между средами Python 2 и Python 3

  1. Создайте среду Python 2 с именем py2, установите Python 2.7:…
  2. Создайте новую среду с именем py3, установите Python 3.5:…
  3. Активируйте и используйте среду Python 2. …
  4. Деактивируйте среду Python 2. …
  5. Активируйте и используйте среду Python 3.

Почему по умолчанию установлен Python 2.7?

Причина, по которой Python 2 вызывается при запуске python, лежит в одном из исторических моментов PEP 394 — команда «python» в Unix-подобных системах: Команда python всегда должна вызывать Python 2 (для предотвращения трудно диагностируемых ошибок при запуске кода Python 2 на Python 3).

12 июня, 2017 12:04 пп
7 456 views
| Комментариев нет

Python

Язык программирования Python был разработан в конце 1980-х, первый релиз вышел в 1991 году. Python назван в честь британской комедийной группы Monty Python и задуман как преемник императивного языка программирования ABC. Первая версия Python уже поддерживала обработку исключений, функции и классы с наследованием.

В этом руководстве вы узнаете, что нужно учитывать при переносе кода с Python 2 на Python 3 и как поддерживать код, совместимый с обеими версиями.

Кратко о версиях Python

Python 2 вышел в 2000 году. Новые функции этой версии позволили сделать процесс разработки более гибким и инклюзивным.

Версия Python 3 – будущее языка Python; в настоящее время эта версия находится в разработке. Выпущенная в конце 2008 года версия Python 3 учитывает и исправляет структурные недостатки предыдущих релизов. Тем не менее, внедрение Python 3 происходило довольно медленно, поскольку эта версия не совместима с Python 2.

Версия Python 2.7 вышла в 2010 году как последний релиз 2.x. Цель Python 2.7 – предоставить пользователям Python 2.x возможность переносить функции на Python 3, обеспечивая частичную совместимость между этими версиями.

Читайте также: Python 2 vs Python 3: краткий обзор и практические соображения

Начало работы с Python 2.7

Чтобы поддерживать Python 2 и Python 3 одновременно или полностью перейти на Python, необходимо убедиться, что код Python 2 полностью совместим с Python 2.7.

Сегодня многие разработчики пользуются исключительно кодом Python 2.7. Вы должны убедиться, что код, который поддерживается только более ранними версиями, корректно выполняется и совместим со стилем Python 2.7.

Обеспечить совместимость кода с Python 2.7 особенно важно, потому что это единственная версия Python 2, которая до сих пор поддерживается и исправляется. Если вы используете более раннюю версию Python 2, вам придется самостоятельно решать проблемы и искать способы исправления ошибок, поскольку версии 2.х больше не поддерживаются и не получают исправлений багов.

Кроме того, некоторые инструменты, которые облегчают перенос кода (например, пакет Pylint, который ищет ошибки в коде), не поддерживаются версиями Python до 2.7.

Важно иметь в виду следующее: хотя версия Python 2.7 поддерживается в настоящее время, её поддержка прекратится в 2020 году (согласно описанию релиза в PEP 373).

Пробный переход

Создание тестового кода является важной частью переноса кода Python 2 на Python 3. Если вы используете несколько версий Python, тестовый код должен покрывать все эти версии.

В рамках тестирования можно добавить интерактивные случаи Python в документацию всех функций, методов, классов и модулей, а затем использовать встроенный модуль doctest, чтобы проверить, как они работают.

Также можно использовать пакет coverage.py для отслеживания покрытий модуля. Этот инструмент следит, какие части кода были выполнены и какие части могли быть выполнены (но этого не произошло). Coverage.py может выводить результат в командной строке или выдавать HTML-вывод. Обычно этот пакет используется для измерения эффективности тестов; он сообщает, какие части кода выполняются при тестировании, а какие нет.

Имейте в виду: стремиться к 100% -му покрытию не нужно. На данном этапе нужно достаточно просто убедиться в покрытии запутанного и сложного кода. Результата в 80% будет вполне достаточно.

Различия между Python 2 и Python 3

Зная разницу между Python 2 и Python 3, вы сможете использовать новые функции и обеспечить правильный перенос кода.

Основные отличия описаны в статье Python 2 vs Python 3: краткий обзор и практические соображения. Более подробную информацию можно найти в официальной документации Python.

При переносе кода следует учитывать несколько изменений в синтаксисе.

print

В Python 2 print является оператором, а в Python 3 – функцией (print()).

Python 2 Python 3
print “Hello, World!” print(“Hello, World!”)

exec

Оператор exec в Python 3 становится функцией с поддержкой локальных и глобальных переменных.

Python 2 Python 3
exec code exec(code)
exec code in globals exec(code, globals)
exec code in (globals, locals) exec(code, globals, locals)

/ и //

Python 2 выполняет целочисленное деление с помощью оператора /, а Python 3 – с помощью //.

Python 2 Python 3
5 / 2 = 2 5 / 2 = 2.5
5 // 2 = 2

Чтобы использовать эти операторы, импортируйте division модуля __future__:

from __future__ import division

raise

В Python 3 для добавления исключений с аргументами требуются круглые скобки; строки не могут использоваться в качестве исключений.

Python 2 Python 3
raise Exception, args raise Exception
raise Exception(args)
raise Exception, args, traceback raise Exception(args).with_traceback(traceback)
raise “Error” raise Exception(“Error”)

except

В Python 2 было сложно перечислить несколько исключений, но Python 3 это уже не так. Обратите внимание: в Python 3 as явно используется вместе с except.

Python 2 Python 3
except Exception, variable: except AnException as variable:
except (OneException, TwoException) as variable:

def

В Python 2 функции могут принимать последовательные типы данных (например, кортежи или списки). В Python 3 эта функция отсутствует.

Python 2 Python 3
def function(arg1, (x, y)): def function(arg1, x_y): x, y = x_y

expr

Синтаксис backtick Python 2 не поддерживается в Python 3. Вместо этого используются repr() или str.format().

Python 2 Python 3
x = `355/113` x = repr(355/113):

Форматирование строк

В Python 3 меняется синтаксис форматирования строк.

Python 2 Python 3
“%d %s” % (i, s) “{} {}”.format(i, s)
“%d/%d=%f” % (355, 113, 355/113) “{:d}/[:d}={:f}”.format(355, 113, 355/113)

Читайте также: Форматирование строк в Python 3

Классы и объекты

В Python не нужно указывать объект.

Python 2
class MyClass(object):
pass
Python 3
class MyClass:
pass

Метаклассы указываются с помощью ключевого слова metaclass.

Python 2
class MyClass:
__metaclass__ = MyMeta
class MyClass(MyBase):
__metaclass__ = MyMeta
Python 3
class MyClass(metaclass=type):
pass
class MyClass(MyBase, metaclass=MyMeta):
pass

Обновление кода

Существует два инструмента для автоматического обновления кода до Python 3. При этом код остаётся совместимым с Python 2. Эти инструменты – future и modernize. Каждый из этих инструментов ведет себя по-разному: future включает поддержку лучших функций Python 3 в Python 2, а modernize работает с  подмножествами Python, которые используют модуль six.

Эти инструменты для обработки переноса кода могут выявить и исправить возможные проблемы и неясности.

Вы можете запустить инструмент во время тестирования, чтобы проверить код и убедиться, что автоматические изменения сделаны правильно. После прохождения тестов вы можете преобразовать свой код.

После этого следует просмотреть код и убедиться, что он учитывает все изменения синтаксиса, описанные в предыдущем разделе.

При использовании модуля future добавьте оператор import во все модули Python 2.7.

from __future__ import print_function, division, absolute_imports, unicode_literals

Это обеспечит соответствие кода Python 2 синтаксису Python 3.

Также можно использовать пакет pylint для выявления потенциальных проблем в коде. Этот пакет содержит сотни индивидуальных правил, которые охватывают широкий спектр потенциальных ошибок (включая правила PEP 8).

Код может содержать некоторые конструкции, которые могут запутать pylint и инструменты, используемые для автоматической миграции.

Непрерывная интеграция

Если вы собираетесь поддерживать свой код для нескольких версий Python, будьте очень внимательны, как можно чаще запускайте unittest путем непрерывной интеграции (а не вручную).

Если вы используете пакет six для поддержки совместимости с Python 2 и 3, создайте несколько сред для тестирования.

Одним из популярных средств управления средой является пакет tox. Он проверит установку пакета в различных версиях Python, проведет тесты в каждой среде и предоставит интерфейс для серверов непрерывной интеграции.

Заключение

Важно помнить, что чем больше внимания разработчиков и сообщества будет уделено версии Python 3, тем больше она будет соответствовать потребностям программистов. При поддержке кода версиями Python 2 и Python 3 возникают различные ошибки, которые со временем станет труднее исправлять.

Tags: Python 2, Python 2.7, Python 3

Многие сталкиваются с проблемой запуска 2 и 3 версии питона в виндовс. Большая часть софта написана на 2 версии Python, но встречаются хорошие проги на 3.

Допустим у нас установлены версии Python 2.7 и 3.6. Первое что нужно сделать, это добавить C:Python36;C:Python36Scripts;C:Python27;C:Python27Scripts к переменной среды PATH.

Для «тех кто в танке» — это находится здесь ( Windows7 ): Пуск — Панель управления — Система — Дополнительные параметры системы — Переменные среды — Системные переменные. Ищем Path жмём изменить и добавляем вышеописанные строки.

Прекрасно, теперь перейдите в C:Python36, чтобы переименовать python.exe в python3.exe, а также в C:Python27, переименовать python.exe в python2.exe.

Запускаем окно командной строки cmd. Чтобы автоматически распознавалась версия Python всего лишь нужно будет вызвать скрипт командами:

python2 script.py или python3 script.py

Для примера я переписал прогу viSQL со второй версии питона на 3.
Проверяем работоспособность. Для этого перемещаемся в нужный каталог и вводим команду запуска:

3.png

33.png

Ларчик просто открывался )

explorer


  • #2

Вышеописанный способ не идеальный. Например, если тулза попросит поставить зависимость, то командой pip install «имя пакета» у вас ничего не выйдет. Дело в том что в самом pip.exe зашит путь по умолчанию.
Соответственно другой выход есть. Нужно запустить команду pip install «имя пакета» предварительно зайдя в каталог, где находится pip.exe

pip.png

Но есть и хорошая новость для ленивых, и не любящих лишнее клацание по клаве.

Есть другой вариант, в котором ничего с патчами мутить не нужно.
Есть программа WinPython

При установке создаётся папка, в которой питон и ещё куча других инструментов запускаются прямо из папки, то есть портабл-версия.
Вот так выглядит содержимое папки

win.png

На этом всё ;)

  • #3

На самом деле, все еще проще. py -2 или py -3 , для запуска той или иной версии интерпретера.

momentomori


  • #4

помидорами не кидайтесь т.к. мои знания даже не 0 а больше в минус уходят, могу только косячить) Но не буду оправдываться больше, ближе к делу. Устанавливаю питон, то что было в «системные переменной» удалил(почти случайно), стал искать что там было в инете, самое близкое к тосу что помню было C:Windowssystem32;C:Windows;C:Python27Scripts (C:Python27Scripts-это уже сам добавил). Видео смотрел, все вроде так, но почему то все равно пишет так(скрин). Что может быть не так? я уже раз 30 по разному пробовал и версии менял и значения «системные переменной», одна беда. Я в тупике.

Скриншот 03-10-2018 173731.png

Скриншот 03-10-2018 174731.png

питон тут

explorer


  • #5

Устанавливаю питон, то что было в «системные переменной» удалил(почти случайно), стал искать что там было в инете, самое близкое к тосу что помню было C:Windowssystem32;C:Windows;C:Python27Scripts (C:Python27Scripts-это уже сам добавил).

В переменных средах должно быть C:Python27;C:Python27Scripts; то есть 2 пути и к папке с питоном и к скриптам

momentomori


  • #6

В переменных средах должно быть C:Python27;C:Python27Scripts; то есть 2 пути и к папке с питоном и к скриптам

Спасибо. А перед этим должна быть какая стандартная строка? Это я так понимаю ей в продолжение, но я попробовал так на всякий, ситуация не изменилась. Скрин приложу как у меня. Но варианты разные конечно пробовал(не факт что правильные) Хотел восстановление сделать, но уже столько раз менял что вчерашнего дня нет уже. В инете тоже везде по разному пишут

Скриншот 03-10-2018 210849.png

explorer


  • #7

Спасибо. А перед этим должна быть какая стандартная строка? Это я так понимаю ей в продолжение, но я попробовал так на всякий, ситуация не изменилась. Скрин приложу как у меня. Но варианты разные конечно пробовал(не факт что правильные) Хотел восстановление сделать, но уже столько раз менял что вчерашнего дня нет уже. В инете тоже везде по разному пишут

Когда что-то меняешь и не очень в этом разбираешься, то лучше всегда копировать в текстовый файл. Остальные патчи конечно не нужно было стирать, нужно вернуть от Windows патч.
C:Windowssystem32;C:Windows;

Раз сразу не получилось, удаляйте питон, при переустановке сразу галочкой можно пометить установку патчей.
Кстати восстановление системы windows можно сделать — откатить на тот день, когда ещё ничего не делали.

momentomori


  • #8

Когда что-то меняешь и не очень в этом разбираешься, то лучше всегда копировать в текстовый файл. Остальные патчи конечно не нужно было стирать, нужно вернуть от Windows патч.
C:Windowssystem32;C:Windows;

Раз сразу не получилось, удаляйте питон, при переустановке сразу галочкой можно пометить установку патчей.
Кстати восстановление системы windows можно сделать — откатить на тот день, когда ещё ничего не делали.

всё сделал, спасибо) Щас дальше буду колдовать

Понравилась статья? Поделить с друзьями:
  • Как переключить количество ядер в компьютере windows 10
  • Как переключить язык в видео проигрывателе windows
  • Как переключить ядра на windows 10 на ноутбуке
  • Как переключить mac os на windows x при запуске
  • Как переключить кнопки мыши на windows 10