1

I have a batch script that is just toggles my python pathing. When I run it a second time, my variable doesn't get set but the string I want it to be set to is echoed onto the console.

First time running the script:

C:\Users\Hai\Desktop>FOR /F "delims=" %I IN ('Python -V') DO (
setlocal
 set "ver=%I"
)

C:\Users\Hai\Desktop>(
setlocal
 set "ver=Python 3.6.3"
)

Second time running same batch file without closing console:

C:\Users\Hai\Desktop> chPythonVer.bat

C:\Users\Hai\Desktop>FOR /F "delims=" %I IN ('Python -V') DO (
setlocal
 set "ver=%I"
)
Python 2.7.15

This is how I'm setting my variable:

FOR /F "delims=" %%I IN ('Python -V') DO (
    setlocal
    set "ver=%%I"
)

echo the current version pathed is %ver%

SET /P c=would you like to switch to the other version? [y/n] 
IF /I "%c%" EQU "y" (
    IF "%ver%" EQU "Python 3.6.3" (
        endlocal
        set PATH= ...
        echo switched to Python 2.7.15
        pause
    ) ELSE (
        endlocal
        set PATH= ...
        echo switched to Python 3.6.3
        pause
    )   
) ELSE IF /I "%c%" EQU "n" (
    endlocal
    pause
)
1

1 Answer 1

2

Firstly, it is a bad idea to set variable names to existing environment variable names. i.e path

You would also need delayedexpansion as you are setting a variable in a code block. So rename PATH to myPATH:

@echo off
setlocal enabledelayedexpansion
FOR /F "delims=" %%I IN ('Python -V') DO (
    set "ver=%%I"
)

echo the current version pathed is %ver%

SET /P c=would you like to switch to the other version? [y/n] 
IF /I "!c!" EQU "y" (
IF "!ver!" EQU "Python 3.6.3" (
    set mypath= ...
    echo switched to Python 2.7.15
    pause
) ELSE (
    set mypath= ...
    echo switched to Python 3.6.3
    pause
)   
    ) ELSE IF /I "!c!" EQU "n" (
   pause
)

If however you were looking at actually updating the system path temporarily then, ignore the first comment and you should then set path as:

SET PATH=%PATH%;c:\whereever\python is\
Sign up to request clarification or add additional context in comments.

3 Comments

It's not that easy, the python -v presumes it is in the path. If you prepend the other version to the path to override you over time get a very long path - so you have to remove the previous version.
set "PATH=... just updates the PATH variable for the current cmd session, so to permanently change it, take a look at the setx command...
@aschipfl yes, he seems to want it set it locally like that, look at the setlocal/endlocal in his script..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.