3

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.

3 Answers 3

7

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, i.e. Python 3 is installed on the system. If it is nonzero, then Python 3 is not installed.

Sign up to request clarification or add additional context in comments.

4 Comments

I only have python 2.7 installed ! and when I run python -3 --version it return python 2.7 and the errorlevel still 0 !!!!
@SachaDee, python.exe is not py.exe. python.exe does not support -0, -2 or -3 arguments. The Python Launcher py.exe does.
I have tried to run py.exe in my python 2.7, but it's apparently not present !
@SachaDee, You can get 3.7.0 launcher.msi for x86 or x64. Use command msiexec /i launcher.msi ALLUSERS=1 to install as an Admin. If you do not use the ALLUSERS property then it installs to the UserProfile. Tested with 2.7.15 in a Win 7 VM.
2

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

1 Comment

python --version 2>&1 | findstr " 2.7" ? Seems to work for 2 and 3. No temporary file needed.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.