Windows批处理脚本中的嵌套条件

时间:2020-08-23 12:00:16

标签: windows batch-file command-line-arguments

我编写了一个Windows批处理脚本py.bat,该脚本应该运行Python脚本,如有必要,在脚本名称中添加.py扩展名,并传递0、1或2个命令行参数。令人惊讶的是,零参数和单参数情况被正确处理,而二参数情况却没有被正确处理。如有任何建议,我将不胜感激。

@ECHO OFF

REM This script runs a Python script, adding the .py extension to the script name if necessary,
REM and passing 0, 1, or 2 command-line arguments.


:Step1

If EXIST "%1%" (
   set file=%1%
   GOTO Step2
)

If EXIST "%1%.py" (
   set file=%1%.py
   GOTO Step2
)

echo Script '%1%' not found!
GOTO End


:Step2

if "%2" EQU "" (
   call python %file%

) else (
   if "%3%" EQU "" (
      call python %file% %2%
   ) else (
      call python %file% %2% %3%
   )
)

:End

我有一个名为count_args.py的简单Python脚本,它报告命令行参数的数量,并以两种方式运行它-直接和通过py.bat。以下I / O显示批处理脚本不会传递多个命令行参数。

(py38) C:\Phillip\Computer\Python\Code3>python count_args.py
Total number of command-line arguments: 0

(py38) C:\Phillip\Computer\Python\Code3>python count_args.py a
Total number of command-line arguments: 1

(py38) C:\Phillip\Computer\Python\Code3>python count_args.py a b
Total number of command-line arguments: 2

(py38) C:\Phillip\Computer\Python\Code3>py count_args
Total number of command-line arguments: 0
(py38) C:\Phillip\Computer\Python\Code3>py count_args a
Total number of command-line arguments: 1
(py38) C:\Phillip\Computer\Python\Code3>py count_args a b
Total number of command-line arguments: 1

0 个答案:

没有答案
相关问题