我编写了一个批处理脚本,用于检查是否已安装Python,是否尚未安装-它将启动与自身相同的文件夹中包含的Python安装程序。
我正在使用以下代码:
reg query "hkcu\software\Python 2.6"
if ERRORLEVEL 1 GOTO NOPYTHON
:NOPYTHON
ActivePython-2.6.4.8-win32-x86.msi
reg query "hklm\SOFTWARE\ActiveState\ActivePerl\" 1>>Output_%date%_%time%.log 2>&1
if ERRORLEVEL 1 GOTO NOPERL
reg query "hklm\SOFTWARE\Gtk+"
if ERRORLEVEL 1 GOTO NOPYGTK
:NOPERL
ActivePerl-5.10.1.1006-MSWin32-x86-291086.msi 1>>Output_%date%_%time%.log 2>&1
:NOPYGTK
pygtk_windows_installer.exe
但是在某些情况下,即使安装了Python,安装程序也会启动。这是什么问题?
您的代码在完成注册表查询后不会分支。不管第一个if ERRORLEVEL
计算结果如何,下一步始终是进入:NOPYTHON
标签。
Ed:这是一个如何使其工作的示例。想法是添加另一个goto语句,如果需要,该语句将跳过:NOPYTHON
标签。
reg query "hkcu\software\Python 2.6"
if ERRORLEVEL 1 GOTO NOPYTHON
goto :HASPYTHON
:NOPYTHON
ActivePython-2.6.4.8-win32-x86.msi
:HASPYTHON
reg query "hklm\SOFTWARE\ActiveState\ActivePerl\" 1>>Output_%date%_%time%.log 2>&1
对于那些只想简单检查一下是否已安装Python并可以执行而无需花费时间的人,请在您的批处理文件中:
:: Check for Python Installation
python --version 2>NUL
if errorlevel 1 goto errorNoPython
:: Reaching here means Python is installed.
:: Execute stuff...
:: Once done, exit the batch file -- skips executing the errorNoPython section
goto:eof
:errorNoPython
echo.
echo Error^: Python not installed
这是我的方法。
python -V
命令将返回版本号,借助于/v
开关的find命令将搜索Python
的省略,并且还有一个普通的不带该开关的语言。
@echo off & title %~nx0 & color 5F
goto :DOES_PYTHON_EXIST
:DOES_PYTHON_EXIST
python -V | find /v "Python" >NUL 2>NUL && (goto :PYTHON_DOES_NOT_EXIST)
python -V | find "Python" >NUL 2>NUL && (goto :PYTHON_DOES_EXIST)
goto :EOF
:PYTHON_DOES_NOT_EXIST
echo Python is not installed on your system.
echo Now opeing the download URL.
start "" "https://www.python.org/downloads/windows/"
goto :EOF
:PYTHON_DOES_EXIST
:: This will retrieve Python 3.8.0 for example.
for /f "delims=" %%V in ('python -V') do @set ver=%%V
echo Congrats, %ver% is installed...
goto :EOF