【问题标题】:batch file to check if Python is installed批处理文件以检查是否安装了 Python
【发布时间】:2011-02-07 10:59:29
【问题描述】:

我编写了一个批处理脚本来检查 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,安装程序也会启动。这里有什么问题?

【问题讨论】:

    标签: windows installation


    【解决方案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 在您的路径中,这会跳过困难的部分
    • 另外,这并不能区分 Python 2 和 3,这在很多情况下是必要的。
    【解决方案2】:

    注册表查询完成后,您的代码不会分支。无论第一个 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  
    

    【讨论】:

      【解决方案3】:

      这是我的方法。

      python -V 命令会返回版本号,find 命令在/v 开关的帮助下会搜索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
      

      【讨论】:

      • @Michael Mrozek 的评论也适用于此处。 Python 安装但未添加到 Path 的可能性总是很高。因此,非技术最终用户将陷入安装和脚本验证的循环中,而不知道路径问题。
      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多