最全Windows下通过bat脚本执行python程序(从编写到执行到拓展到更换图标全过程)_bat 脚本 python
@echo off
setlocal enabledelayedexpansion
:: 设置Python脚本文件名
set "PY_SCRIPT=your_script.py"
:: 设置图标文件名
set "ICO_FILE=your_icon.ico"
:: 获取当前脚本所在路径
for %%I in ("%~dp0.") do set "SCRIPT_DIR=%%~fI"
:: 设置Python和Python库的路径
set "PYTHON_DIR=C:\Python39"
set "PYTHON_LIB=%PYTHON_DIR%\python39.zip;%PYTHON_DIR%\DLLs;%PYTHON_DIR%\lib"
:: 设置执行Python的命令
set "PYTHON_EXE=%PYTHON_DIR%\python.exe"
:: 设置完整的Python路径和程序参数
set "PYTHON_CMD=%PYTHON_EXE% -X -OO -B -q -I "%PYTHON_LIB%" -E"
:: 设置执行脚本的命令,包括路径、脚本文件和程序参数
set "RUN_CMD=%PYTHON_CMD% "%SCRIPT_DIR%\%PY_SCRIPT%" %*"
:: 设置图标文件的完整路径
set "ICO_CMD=/select,"%SCRIPT_DIR%\%ICO_FILE%" "
:: 创建快捷方式
call cecho Creating shortcut for ^>^> "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"
call cecho Updating icon for ^>^> "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"
:: 创建快捷方式并更新图标
"%SCRIPT_DIR%\CreateShortcut.exe" /silent "%SCRIPT_DIR%\%PY_SCRIPT%.py" "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"
call cecho Updating icon for ^>^> "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"
:: 更新快捷方式的图标
call cecho Updating icon for ^>^> "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"
(
echo Set oLink = CreateObject("WScript.Shell").CreateShortcut(WScript.Arguments(0))
echo oLink.IconLocation = WScript.Arguments(1)
echo oLink.Save
) > "%TEMP%\update_icon.vbs"
cscript //NoLogo "%TEMP%\update_icon.vbs" "%SCRIPT_DIR%\%PY_SCRIPT%.lnk" "%ICO_CMD%"
:: 清理临时文件
call cecho Cleaning up ^>^> "%TEMP%\update_icon.vbs"
del "%TEMP%\update_icon.vbs"
:: 设置快捷方式的目标为执行命令
call cecho Updating target for ^>^> "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"
for /f "tokens=1,* delims=:" %%A in ('findstr /n .* "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"') do (
set "line=%%A"
set "modified=%%B"
)
set "modified=%modified:Target^=Shortcut=%RUN_CMD%"
(for /f "delims=:" %%A in ('findstr /n .* "%SCRIPT_DIR%\%PY_SCRIPT%.lnk"') do (
set "line=%%A"
setlocal enabledelayedexpansion
echo !line:*:=!^|findstr /C:"Target=" /C:"IconLocation=" /C:"Shortcut=" >nul || echo !modified!
endlocal
)) >"%TEMP%\shortcut.lnk"
move /y "%TEMP%\shortcut.lnk" "%SCRIPT_DIR%\%PY_SCRIPT%.lnk" >nul
:: 设置快捷方式的参数
call cecho Updating arguments for ^>^> "%SCRIPT_DIR%\%PY_SC
评论已关闭