Switch between different Python versions in Window

2019-02-20 06:58发布

问题:

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

回答1:

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.



回答2:

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.