简体   繁体   中英

Batch Script to Execute script with python 3 if available else python 2

Trying to create a batch script for windows that runs a program with python3 if available else python2.

I know the script can be executed with $py -2 script.py and py3 with $py -3 script.py .

and if I run py -0 , it returns all the python versions.

How do I build this script?

I do not want to check if the python directory is available or not, I'd prefer to check in a way that is python location agnostic.

Not a full solution, but a method to detect which version of Python is installed:

You can check if Python 3 is installed by running py -3 --version and then checking the %ERRORLEVEL% variable in the batch script. If it is 0, then py -3 --version was successful, ie Python 3 is installed on the system. If it is nonzero, then Python 3 is not installed.

Piping directly python.exe --version to find or findstr is not working (with python 2.7).

Building dinamicaly and running a python script that return the version, will enable this piping !

The solution :

@echo off
set "$py=0"
call:construct

for /f "delims=" %%a in ('python #.py ^| findstr "2"') do set "$py=2"
for /f "delims=" %%a in ('python #.py ^| findstr "3"') do set "$py=3"
del #.py
goto:%$py%

echo python is not installed or python's path Path is not in the %%$path%% env. var
exit/b

:2
echo running with PY 2

exit/b

:3
echo running with PY 3

exit/b

:construct
echo import sys; print('{0[0]}.{0[1]}'.format(sys.version_info^)^) >#.py

You can do it without temporary file

set PYTHON_MAJOR_VERSION=0
for /f %%i in (python -c "import sys; print(sys.version_info[0])"') do set PYTHON_MAJOR_VERSION=%%i

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