简体   繁体   中英

Batch for trying two python versions

The system will have a possible Python version of 2.4.5 or 2.7.9 only. I'm trying to write a batch error handling to try use python 2.7.9 first, and if that fails, use python 2.4.5.

Conditions

System has company installed software and will only have Python 2.4.5 or Python 2.7.9. And I won't know which one, so my scripts have to be backwards compatible.

This is what I have

rem
@echo off

echo Building
"%COMMONPROGRAMFILES%\CompanyName\python\python27\python.exe" build.py

IF ERRORLEVEL 1 GOTO TRY-PYTHON-24
IF ERRORLEVEL 0 GOTO FINISHED-BUILDING

:TRY-PYTHON-24
"%COMMONPROGRAMFILES%\CompanyName\python\python24\python.exe" build.py

IF ERRORLEVEL 0 GOTO FINISHED-BUILDING


:FINISHED-BUILDING:
echo Done
...more code...

Expected Result

Try and use Python 2.7.9 first, if there is ERRORLEVEL 1 , then try Python 2.4.5. There won't be an error there. Is this the correct way of writing a batch version of try except statement like Python?

Such as..

try:
    ...Python 2.7.9...
except:
    ...Python 2.4.5...

Sources

I wrote this based on Microsoft's guide ( https://support.microsoft.com/en-us/kb/39585 ). But I'm unsure if this is the best method to a try except on two versions of Python.

you can use IF EXIST :

set "p279="%COMMONPROGRAMFILES%\WatchGuard\python\python27\python.exe""
set "p245="%COMMONPROGRAMFILES%\WatchGuard\python\python24\python.exe""

if exist %p279% (
   set "python=%p279%"
) else (
  set "python=%p245%"
)

call %python% build.py

I can't speak to the general case of try-except constructs in batch files, but there is a much simpler way to solve this particular problem: use the PATH variable. The code shown can be replaced with

@echo off
set "PATH=%PATH%;%COMMONPROGRAMFILES%\WatchGuard\python\python27"
set "PATH=%PATH%;%COMMONPROGRAMFILES%\WatchGuard\python\python24"
python build.py || exit /b

rem ... more code ...

Setting PATH this way makes the batchfile interpreter automatically look for python.exe in both of the directories where it could be. If both versions of Python are installed, it will take the one earlier in the list, ie the one in ...\\python27 . (Note that this means if there is some other version of Python installed in a directory that already appeared in PATH when the script was invoked, that one will be used. This is probably what someone who set their system up that way wants.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM