我有一个批处理脚本,当给定输入“ edit”时,它应该回显“ hello”作为一种调试,并在记事本中打开批处理脚本文件。但是,由于某种无法解释的原因,脚本无论如何都不会响应if语句。如何获得对“编辑”输入的响应?
REM @ECHO OFF
cd/
cd projects\py_test
ECHO Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
ECHO.
SET /P name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
REM @ECHO OFF
cmd /k IF %name%==edit GOTO EDIT
REM IF EXIST %name% py %name%
REM IF NOT EXIST %name% echo [101mERROR: The requested file could not be found. Make sure the file exists in "C:\Projects\py_test\" and that the filename includes the ".py" extension.[0m
@ECHO OFF
:EDIT
ECHO HELLO
notepad projects-py_test-dot_start.bat`
答案 0 :(得分:1)
首先,为什么要所有REM @ECHO OFF
个?看起来很丑,尤其是当它们都是大写字母时。
然后,您是否出于没有真正原因而为if语句运行cmd /k
?使用变量名时,您需要将if语句变量用双引号引起来,以消除可能的空格:
@echo off
cd /d "C:\projects\py_test"
echo Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
echo/
set /p name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
if defined name set "name=%name:"=%"
if /i "%name%"=="edit" goto edit
goto :EOF
:edit
echo hello
notepad echo "%~f0"
,但是通过猜测您只是想启动一个python脚本(如果存在),否则对其进行编辑,那么我会改用不带标签的该版本。它只是检查键入的名称是否存在(希望用户键入带有扩展名的完整脚本),否则,我们添加了扩展测试,以防用户仅键入名称而不键入扩展名。
@echo off
cd /d "C:\projects\py_test"
echo Use this batch script to lauch Python modules living in "C:\Projects\py_test\" ONLY.
echo/
set /p name="Type file name with file extension .py to start or type EDIT to edit this .bat: "
if defined name set "name=%name:"=%"
if /i "%name%"=="edit" notepad "%~f0"
if exist "%name%" (
python "%name%"
) else (
if exist "%name%.py" (
python "%name%.py"
) else (
echo "%name%" does not exist
)
)