【问题标题】:Variable Not Set When Same Batch Script Run Twice同一批处理脚本运行两次时未设置变量
【发布时间】:2023-04-09 11:53:01
【问题描述】:

我有一个批处理脚本,它只是切换我的 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】:

首先,将变量名称设置为现有环境变量名称是一个非常非常糟糕的主意。即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\

【讨论】:

  • 这并不容易,python -v 假定它路径中。如果您将其他版本添加到路径中以随着时间的推移覆盖您,则会得到一条很长的路径 - 因此您必须删除以前的版本。
  • set "PATH=... 只是更新 当前cmd 会话PATH 变量,因此要永久更改它,请查看setx command...
  • @aschipfl 是的,他似乎希望它像这样在本地设置,看看他脚本中的setlocal/endlocal..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多