批处理脚本以使用python 3执行脚本(如果可用),否则python 2

时间:2018-09-06 20:44:37

标签: python batch-file

尝试为Windows创建批处理脚本,该脚本使用python3运行程序(如果可用,则使用python2)。

我知道脚本可以用$py -2 script.py执行 和py3和$py -3 script.py

如果我运行py -0,它将返回所有python版本。

如何构建此脚本?

我不想检查python目录是否可用,我宁愿以与python位置无关的方式进行检查。

2 个答案:

答案 0 :(得分:4)

不是完整的解决方案,而是一种检测安装了哪个版本的Python的方法:

您可以通过运行py -3 --version然后检查批处理脚本中的%ERRORLEVEL%变量来检查是否安装了Python 3。如果为0,则py -3 --version成功,即系统上安装了Python 3。如果非零,则说明未安装Python 3。

答案 1 :(得分:1)

直接python.exe --versionfindfindstr的管道不起作用(使用python 2.7)。

构建动力学并运行返回版本的python脚本,将启用此管道!

解决方案:

@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