Switch between different Python versions in Windows 10 cmd - python

I don't like the other post.
because it involves renaming python executables.

Here's my discoveries.
Step 1. Go to System Properties. Click on Environment Variables
Step 2. Add new variables, such as PYTHON_27_HOME
PYTHON_27_HOME:%ProgramFiles%\Python27\
PYTHON_36_HOME:%ProgramFiles%\Python36\
PYTHON_HOME:%PYTHON_27_HOME%
In my case, PYTHON_27_HOME(Python 2.7) is pointing to C:\Program Files\Python27\. You can replace this with your own path to python. %PYTHON_HOME% has a default value pointing to %PYTHON_27_HOME%, which is the path for Python 2.7. That's my preference, feel free to adjust accordingly. Be aware that there're 32-bit and 64-bit python. Please use %PROGRAMFILES% for path to C:\Program Files and %PROGRAMFILES(X86)% for path to C:\Program Files (x86).
Step 3. Select PATH and click on Edit. PATH
Step 4. Click on New and add %PYTHON_HOME%. %PYTHON_HOME% will be added to PATH automatically every time you launch a command prompt.
In order to switch between different versions of python in cmd, here's the trick.
Step 5. I created a batch file with
#echo off
:: Switch Python version
DOSKEY python27=SET PATH=%PYTHON_27_HOME%;%PATH%
DOSKEY python36=SET PATH=%PYTHON_36_HOME%;%PATH%
Basically, it disables echo and creates two alias. In batch file any string after :: is the comments. Every time, python27 or python36 is called, it re-exports %PATH% with the new Python path. Save it as profile.bat. You can name it whatever you want.
Step 6.
Search for regedit (Registry Editor). Click on Edit > New > String Value. Give AutoRun as the Value name and %USERPROFILE%\profile.bat as the Value data. Here, please put your actual path value to the profile.bat we just created. So, whenever a command prompt is opened, it automatically loads profile.bat, which creates those two alias in the script.
Step 7. Close any command prompt you're using or just open a new command prompt. This is because your changes will not affect opened cmd window. Environment changes only happens to new CMD.
Step 8. Verify your results here.
If you're using different Java versions, same trick applies, too. Find my javac environment setting here.

I think the easiest way to support various versions of Python, as well as other languages, is the asdf version manager. It allows you to set a version of Python globally, as well as in each project folder. This means that you can set your Python version to dynamically change based upon the folder you're working in.
asdf version manager
I haven't used Windows for almost 20 years, but I've heard that Windows 10 sports an Ubuntu-based subsystem for Linux. I don't know if asdf will work with that, but it is worth a try. Just use the instructions for setting asdf up with bash.

TL;DR: Use a symbolic link to youre current version and put that on your path instead.
Linux has the alternatives command to switch versions globally, but I do this:
Install Python variants under C:\Python\Python38, C:\Python\Python36 etc
Set your PATH to include C:\Python\Current;C:\Python\Current\Scripts
Have a batch file like this to switch versions:
#echo off
echo 1. Python 3.8
echo 2. Python 3.6
set /p ver="Enter Version: "
if [%ver%]==[1] (
SET FOLDER=C:\Python\Python38
) ELSE if [%ver%]==[2] (
SET FOLDER=C:\Python\Python36
) ELSE (
GOTO end
)
if exist C:\Python\Current\nul (
rmdir C:\Python\Current
)
MKLINK /D C:\Python\Current %FOLDER%
:end
The only downside is that MKLINK (and hence the batch file) requires elevated privilages

Related

Different python used in .cmd when file is ran vs. when python is opened directly

On Windows 10:
Hi, I am having an issue with understanding how my computer works with python. When I run a python file in my IDE, Atom, it uses the python from PATH. When I run python in .cmd, it uses the python from PATH. When I execute the same python file from .cmd it uses a python that is not in PATH. Why is it doing this and how can I get it to use the same python? I want everything to use the anaconda python.
I don't understand where the \AppData\ python is coming from?
![
]4
What you see in Control Panel is just a template (if you will). Every process gets those settings when it starts, but it can modify them afterwards. Take the following example:
Start cmd.exe:
1.1. echo %PATH% - will output the inherited value
1.2. set PATH=%PATH%;some_other_dir - will change the inherited value in the current (cmd.exe) process
1.3. Repeat #1.1 - will output the updated value
1.4. Open the Control Panel settings again. You won't see some_other_dir there
To check the current Python process environment (inherited from the parent process), use os.environ. Add in your script:
import os
print(os.environ["PATH"])
So, the non Anaconda Python might actually be in %PATH%.
But the behavior could also be (and I'm leaning towards this one) due to [Wikipedia]: File association. For more details, check [SO]: How do I set “default App” for a file extension to an “.exe” on Windows 10 after April 2018 update (#CristiFati's answer).

Other than swapping order of paths to python folders in system variable 'PATH' - what are the ways to swap python versions?

I can change the order to python2,3 folders in the system PATH variable. But what are other ways to do this?
There should be more elegant way to change versions of python i want to run.
e.g. in console:
python file.py #will run python2
and after i change python command to use python3, it should be the same:
python file.py #will use python3
I suppose you are trying to run your script with the correct interpreter depending on which python version was used. On Unix/Linux this is done with a so called “shebang” which is written in the very first line of the file. E.g.:
#!/usr/bin/env python3.6
If your installation of Python3 is newer than Python 3.3 you can use the python launcher for windows, which should be able to launch the correct version of Python depending on the shebang, even on window.
Also see here for more informations on shebangs.
If your concern is what Python version is executed when calling python in a console, then an alias or a stub script are the two ways to go.
This post will explain you how you can do this on Windows.
The alias way, just like it would be on a Unix system, is to create an alias, either temporary to the session or permanent, so that python now means C:\Python27\python, or whatever version you want.
The script approach consists in putting a script named python in a directory referred to in your PATH, and have that script run the right version of Python.
I highly doubt that this will affect all the batch scripts that call python, but it will definitely fire the right Python when you'll type python in a console.
Now, if you're concerned about what version a script is executed with, you can specify an explicit version with a shebang line, or manually select it by right-clicking the .py file and clicking open with.

How can I change the Python version in Visual Studio Code?

These are my settings:
User Settings
{
"atomKeymap.promptV3Features": true,
"editor.multiCursorModifier": "ctrlCmd",
"editor.formatOnPaste": true,
"python.pythonPath": "python3",
"command": "python3",
}
Workspace Settings
{
"python.pythonPath": "${workspaceFolder}/env/bin/python3.6",
"git.ignoreLimitWarning": true
}
tasks.json
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "0.1.0",
"command": "python3",
"isShellCommand": true,
"args": ["${file}"],
"showOutput": "always"
}
If I use the debug console, the version and path is right:
But the output always defaults to "python2.7", no matter what I do.
How can I fix this?
Under the view menu select 'show command pallet'. One of the commands you can then select from the command palette is 'Python: Select Interpreter'. Selecting this option will allow you to choose which version of python to use.
UPD. First, read the update #1 part in the bottom
(Try update#1 first) Looking at your screenshots I see you are using Code Runner extension. And I guess that is the way you are launching your programs.
I don't know how it works internally, but adding this line into Code-Runner extension setting.json file fixed it:
"code-runner.executorMap.python": {...
"python": "python3 -u",
...}
Found it in Code-Runner GitHub repository: https://github.com/formulahendry/vscode-code-runner/issues/366
If you type "python --help", you'll see "-u" flag stands for "unbuffered binary stdout and stderr..." - don't know why it matters here.
Update #1. This became not so convenient further - I started using python's virual environments and the solution above couldn't launch these environments, cause python3 (symlink) is always linking to the same python environment.
The solution here is to use Code-Runner's supported customized parameters, so you should change "python" line in it's settings.json to:
...
"python": "$pythonPath $fullFileName",
...
Tot's answer is what worked for me on windows 10, with a few modifications.
File -> Preferences -> Settings
Type in "python.pythonPath" in the search bar.
Change it to what you normally run python with from the command line. If you have your Path environment variable set, that's just python. If not, it's likely the full path to the executable.
This solution is for Mac and Linux:
To change your Python version from 2.7 to 3 do this:
In Vscode click on file > preferences > settings.
On the right side click on the ... (the three dots) and select (open settings.json)
In the search bar type code-runner.executorMap.
You can only change the settings on the right side.
After the last setting type a comma then
"code-runner.executorMap" and hit enter, this will copy all the settings from the default file.
Look for "python" and change the command next to it to "python3".
Save the changes and you should be good to go.
VS Code's terminal using a different python interpreter than the one you've selected
By default, it doesn't know about your interpreter, and will initialize using the default .bashrc or equivalent in the OS.
I found two relevant settings from an issue in Feb 2021.
Checking the second option Python > Terminal: Activate Environment enables automatic activation of virtual environment:
In settings.json it is called "python.terminal.activateEnvironment": true.
Update (8 Aug 2021):
Today when I opened the terminal from VS Code on Windows, it automatically inserted a line of code & C:/Users/[UserName]/[venv]/Scripts/Activate.ps1 to activate the appropriate environment associated with the selected python interpreter!
It appears the aforementioned settings is now the default behavior.
While there are changes to Terminal behavior in the release notes of July 2021 (version 1.59), I don't see virtual environment activation being explicitly mentioned.
The new behavior is documented here, in "Environments and Terminal windows".
"python.pythonPath" has been deprecated
Therefore most previous answers are outdated.
Use "python.defaultInterpreterPath" instead:
2021.6.0 (16 June 2021)
5. Added python.defaultInterpreterPath setting at workspace level when in pythonDeprecatePythonPath experiment. (#16485)
8. Show python.pythonPath deprecation prompt when in pythonDeprecatePythonPath experiment. (#16485)
2020.7.0 (16 July 2020)
9. Prompt users that we have deleted pythonPath from their workspace settings when in Deprecate PythonPath experiment. (#12533)
2020.5.0 (12 May 2020)
6. Do a one-off transfer of existing values for python.pythonPath setting to new Interpreter storage if in DeprecatePythonPath experiment. (#11052)
8. Added prompt asking users to delete python.pythonPath key from their workspace settings when in Deprecate PythonPath experiment. (#11108)
12. Rename string ${config:python.pythonPath} which is used in launch.json to refer to interpreter path set in settings, to ${config:python.interpreterPath}. (#11446)
2020.4.0 (20 April 2020)
13. Added a user setting python.defaultInterpreterPath to set up the default interpreter path when in Deprecate PythonPath experiment. (#11021)
If you wish to set a default python interpreter for all workspaces, open settings with Ctrl+Shift+P, Preferences: Open User Settings and search for Python: Default Interpreter Path. Otherwise, if you want to set it for only the current workspace, use Preferences: Open Workspace Settings instead.
In your case, you wish to set it to ${workspaceFolder}/env/bin/python3.6.
If you edit settings.json directly instead of using the GUI:
{
"python.defaultInterpreterPath": "${workspaceFolder}/env/bin/python3.6"
}
Detailed instructions can be found in the documentation "Manually specify an interpreter", including using environment variables as the interpreter's path.
Several of the answers here explain good approaches, but below are my top 2 recommendations.
Bottom Screen Navigation (ease of access)
I find this the quickest approach; however, it isn't always available for first-time users. If you're already using Python in VS Code, this is usually the easiest way to reach the Python: Select Interpreter menu. On the bottom left of your screen, look for "Python X.X.X". This is the currently detected/configured version of Python for your project, and clicking it brings you to the interpreter menu to change the Python version you're using. At the time of writing, I was using Python 3.9.1 as seen in the snippet below:
Command Palette
As #jmh denoted in his answer, you can also use the 'View' tab to navigate to the Command Palette. In the Command Palette, search for Python: Select Interpreter to bring about the same menu denoted above.
Happy coding!
In VSCode there are two paths of python:
Path that is used when you the python code using green play button up in the top right corner. This path can be set under CTRL+SHIFT+P Python: Select Interpreter.
Path that is used when you type "python" in the terminal, and this is in "Environment Variables" in Windows 10 (Similar locations under Linux and Mac). In Windows 10 you can choose to have several Python versions, usually under C:\Users\YourName\AppData\Local\Programs\Python\Python##. Just make sure you change Environment variables C:\Users\YourName\AppData\Local\Programs\Python\Python## and C:\Users\YourName\AppData\Local\Programs\Python\Python##\Scripts accordingly. This will also affect which pip you use, i.e. a pip that belongs to Python 3.8, or a pip that belongs to Python 3.9. Terminal in VSCode in general pertains to your default terminal I think. So in Windows 10 when you type "python" in CMD Line, it should be the same version as VSCode terminal.
For sanity purposes you should make sure that both "Python: Select Interpreter" and the system environment variables point to the same version of Python.
Bonus goodie in Windows 10. If you don't have environment variable setup, and you type 'python' in VSCode terminal, it'll point to C:\Users\YourName\AppData\Local\Microsoft\WindowsApps\python.exe, which just opens up python link in Windows AppStore 🙄.
Late answer really, if you find difficult to set the python version in VsCode,
If the interpreter didn't show the envname/bin/python or any desired path you want, then go to
VSCODE main page -->file-->preference-->settings
select the ... on the right corner side. You'll see USER SETTINGS, WORKSPACE SETTINGS, YOURAPP_NAME_SETTINGS. click on the your_app_name.
"python.pythonPath":
"/home/Jhon/AllWorksUbuntu/Projects/VX-350/envname/bin/python"
Play on the above to set the correct path. You're good to go!!!
Worked for me (linux user);
Assuming that you have other python versions installed in your system:
Kill the old terminal
Open a new terminal
In the new terminal instead of write "python" to select the interpreter write "python3" or "python3.8"
Looks like put only 'python' will always bring python 2.
Just a preface: VS code was working fine (Using Python 3.x) and seemingly out of the blue it started using Python 2.7. The input() function would not convert the input to a string and that's when I realized what was happening. Typing Python in the terminal window showed 2.7 was running.
For me....
Even though "python.pythonPath" was pointing to a seemingly correct location (C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64), one of my environment variables was pointing to C:\Users\Mike.windows-build-tools\python27.
I deleted the environment variable and reinstalled Python 3.8 from the Microsoft Store and it immediately installed. I got a message from VS Code (it was running) that 3.8 got installed. I clicked Terminal/New Terminal, typed Python and it showed version 3.8. Typed 'Python xxx.py' and the code started working as it had been.
In my case, I checked the python version using
python --version
It showed python 2.x even though my interpreter path was 3.x. So uninstalled python 2.x from my computer through control panel. Then it worked fine for me.
Updating #Isabella answer, using current VSCode 1.65.1 and current python launcher, you can use py -version, for example py -3.8.
Thus, you can make a folder .vscode containing a single file name called settings.json containing
{
"python.defaultInterpreterPath": "py -3.8",
}
In Vscode you can go to preferences > settings, then on the right menu click on the first icon which is JSON. Look for "python.pythonPath" and "python.defaultInterpreterPath" and change the path. To find python3 path, open terminal and execute python3 dummyname. Actually you'll face an error but the point is it will show you the path!
One thing that can also be missed is the shell profile you are using in your terminal where you see the wanted python version vs the profile in your VS Code.
Hold cmd + p and write >Terminal: Select default profile
Select bash or whatever you used to install the python3 version in the terminal at the global level.
Closs the terminal and VS Code and then open it again, this time VS Code will pick the correct version
from the Lower left corner, click on the python, then vscode will navigate you to all python version that installed in your system, and select the right one for you.
Windows: Use py -3.6 --version or to create virtual environment py -3.6 -m venv venv36
Installing Anaconda, then selecting it as the interpreter is an easy way to set Python to the latest version and get the extensions that will make your Jupyter Notebook working.
For Windows Users:
I was recently faced with a similar situation where my newly downloaded python version would not show in the terminal even when I had selected the correct interpreter using 'Python: Select Interpreter'.
Here are the steps I followed that finally made it work:
Go to 'Edit the system variables' in settings.
Under the 'Advanced' tab, click the 'Environment Variables' button.
In the top half of the new window that opens, you will find 'User Variables'.
Find the path of your old python version in there.
Replace it with the path of your new python version.
Now check your python version in the VScode terminal again.

create a python shell environment launcher to use pyQgis

I am trying to modify the shell launcher found at "http://inasafe.linfiniti.com/html/id/developer-docs/platform_windows.html" so that I can use it to directly launch any shell I'd like (in my case, I wanna use the default IDLE gui in Python 27 library folder for windows).
My changes didn't bring me to an acceptable result so far. Here is my version of the launcher, where I should change it?
#echo off
SET PyShell=C:\Programmi\Quantum GIS Lisboa
call "%PyShell%"\apps\Python27\Lib\idlelib\PyShell.pyc
#echo off
SET GDAL_DRIVER_PATH=%PyShell%\bin\gdalplugins\1.9
path %PATH%;%PyShell%\apps\qgis\bin
path %PATH%;%PyShell%\apps\grass\grass-6.4.2\lib
path %PATH%;"%PyShell%\apps\Python27\Scripts\"
set PYTHONPATH=%PYTHONPATH%;%PyShell%\apps\qgis\python;
set PYTHONPATH=%PYTHONPATH%;%PyShell%\apps\Python27\Lib\site-packages
set QGIS_PREFIX_PATH=%PyShell%\apps\qgis
start "Quantum GIS Shell" /B "cmd.exe" %*
My OS is Windows XP, the version of Python is 2.7.3, while Qgis is 1.8 (Lisboa).
I am reeeeally new to Python and stuff, so please forgive my big mistakes if there are some (but I'm pretty sure there are).
Finally the solution was int the line where I specify which program to use as shell. In my case, I found bot "Pyshell.pyc" and "idle.pyw". The second seems to be the right to poit at, as everything works fine now.
So, my personal shell launcher looks like this:
#echo off
SET IDLE=C:\PROGRA~1\QUANTU~1
call "%IDLE%"\apps\Python27\Lib\idlelib\idle.pyw
#echo off
SET GDAL_DRIVER_PATH=%IDLE%\bin\gdalplugins\1.9
path %PATH%;%IDLE%\apps\qgis\bin
path %PATH%;%IDLE%\apps\grass\grass-6.4.2\lib
path %PATH%;"%IDLE%\apps\Python27\Scripts\"
set PYTHONPATH=%PYTHONPATH%;%IDLE%\apps\qgis\python;
set PYTHONPATH=%PYTHONPATH%;%IDLE%\apps\Python27\Lib\site-packages
set QGIS_PREFIX_PATH=%IDLE%\apps\qgis
start "Quantum GIS Shell" /B "cmd.exe" %*
Anyway, this was a workaround to set the environment variables to use PyQGIS, as I had difficulties to set them in the "normal" way.
Unfortuntely, I didn't fix my problem, as I'm still getting errors while importing the "qgis.core" module, while using the original shell launcher through cmd.exe it works, but it's not a good IDE though...

Using Python 3.1 with TextMate

TextMate seems to use the built-in Python version I assume (sys.path doesn't work). How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I need to use TextMate now.
Thanks
TextMate uses the value of the TM_PYTHON variable to find the path to the Python interpreter. A good solution is to take advantage of TextMate's ability to define variables like TM_PYTHON on a per-project basis:
Open a new or existing TextMate Project (File -> New Project or File -> Open)
De-select any file in the project list sidebar.
Click on the Get Info (i) icon in the sidebar. A Project Information pane appears.
Click + to add a new variable.
Enter TM_PYTHON in the Variable field and the full path to the desired python in the Value field (for example, /usr/local/bin/python3.1).
Close the Information window and save the Project (File -> Save Project As).
Then you can add files as needed to the project and they will be run under the chosen python with TextMate Python bundle's Run Script command. You might want to save a Python 3 project, say, for running ad-hoc scripts under Python 3. For bigger projects, you'll want to create a separate TextMate project for it anyway.
To change the Python version used globally within TextMate:
From the TextMate menu bar, open TextMate -> Preferences
click on the Advanced pane
click on the Shell Variable tab
click the + to add a new variable
enter TM_PYTHON in the Variable field and the full path to the python in the Value field (perhaps /usr/local/bin/python3.1)
As Alex points out, you may break other TextMate functionality by changing the Python version globally so the per-project change is probably a better solution.
UPDATE (2010-10-31):
There is another approach that may be easier to use for some projects. The Run command in TextMate's Python bundle appears to respect a shebang line in the file being run. So, instead of modifying TM_PYTHON, you can specify the path to the interpreter to be used by including a first line like this:
#!/usr/local/bin/python3.1
# sample code to show version
import sys
print(sys.version_info)
In many case you would prefer not to hardwire the absolute path but manage use through the normal shell PATH environment variable. Traditionally /usr/bin/env is used for that purpose. However when running under TextMate, your shell profile files are not normally used so any changes to PATH do not show up there including possibly /usr/local/bin or /opt/local/bin or wherever your desired python3 command is located. To get around that, you can add or modify a global PATH shell variable to TextMate -> Preferences (see above) with a value of, say, /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin. Then you can use a more general shebang line like this:
#!/usr/bin/env python3
(This all seems to work with the most recent vanilla TextMate and its Python bundle: no guarantees about earlier versions or with other Python bundles.)
Late to the party, sorry! I take it you want to run the script using TextMate's 'built-in' interpreter? I've found the simplest solution is to add a shebang, which works extremely well;
#!/usr/bin/env python3
for python 3.1 or;
#!/usr/bin/env python
for default system python, although the latter is superfluous for the exercise.
According to this long thread (which was about Python 3.0, and the TextMate version existing back last spring, but I believe is still valid for Python 3.1 and today's TextMate), you can get it done (e.g. via #Ned's answer), but once you do many TextMate commands may well break (because they're written to use Python 2, and Python 3 is not backwards compatible with Python 2 -- for example, the use of reload, which disappeared in Python 3, is repeatedly mentioned in the thread). Still, it might work if you do not use or need much of TextMate's functionality (LaTeX typesetting for example was mentioned as something that totally breaks once you make TextMate use Python 3 instead of Python 2).
the shebang is the best solution, to see where python 3 is installed type in terminal:
which python3
you will get something like this:
/usr/local/bin/python3
if nothing shows up first install python3
and at the top of your script insert:
#!/usr/local/bin/python3
I wanted to achieve this in TextMate version 2.0.23 with the aim to use python3 as the default.
So this is how I could set the TM_PYTHON variable (based on #Ned Deily's answer above):
Open Textmate
Hit CMD + ; to open the settings
Now Add a new Variable with the + sign
4. In the Terminal.app I typed which python3 which gave me /usr/local/bin/python3.
Now whenever I open a python script and hit CMD + R it will execute as a pyhton3 script by default while "honouring" the installed PIP packages.

Categories