同一批处理脚本运行两次时未设置变量

问题描述 投票:0回答:1

我有一个批处理脚本,它只是切换我的 python 路径。当我第二次运行它时,我的变量没有被设置,但我希望将其设置为的字符串会回显到控制台上。

第一次运行脚本:

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"
)

第二次运行相同的批处理文件而不关闭控制台:

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

这就是我设置变量的方式:

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
)
batch-file command-line
1个回答
2
投票

首先,将变量名称设置为现有的环境变量名称是一个坏主意。即

path

当您在代码块中设置变量时,您还需要

delayedexpansion
。因此,将
PATH
重命名为
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
)

但是,如果您正在考虑暂时实际更新系统路径,请忽略第一个注释,然后您应该将路径设置为:

SET PATH=%PATH%;c:\whereever\python is\
© www.soinside.com 2019 - 2024. All rights reserved.