如何在Makefile中确定Python版本?

11

自从Python默认使用版本3以来,有必要使用正确的Python解释器处理版本2代码的执行。我有一个小型Python2项目,在其中使用make配置和安装Python包,所以这里是我的问题:如何在Makefile中确定Python的版本?

这是我想要使用的逻辑: 如果(python.version == 3)则 python2 some_script.py2 否则 python3 some_script.py3

提前感谢!

5个回答

12
python_version_full := $(wordlist 2,4,$(subst ., ,$(shell python --version 2>&1)))
python_version_major := $(word 1,${python_version_full})
python_version_minor := $(word 2,${python_version_full})
python_version_patch := $(word 3,${python_version_full})

my_cmd.python.2 := python2 some_script.py2
my_cmd.python.3 := python3 some_script.py3
my_cmd := ${my_cmd.python.${python_version_major}}

all :
    @echo ${python_version_full}
    @echo ${python_version_major}
    @echo ${python_version_minor}
    @echo ${python_version_patch}
    @echo ${my_cmd}

.PHONY : all

为了支持2.5之前的版本,我使用了python -V - fnokke

10

这里有一个更短的解决方案。在你的Makefile开头写入:

PYV=$(shell python -c "import sys;t='{v[0]}.{v[1]}'.format(v=list(sys.version_info[:2]));sys.stdout.write(t)");

然后,您可以使用$(PYV)将其与IT技术相关内容一起使用。

7
在继续运行制作菜谱之前,我们要检查 Python 版本是否大于 3.5。
ifeq (, $(shell which python ))
  $(error "PYTHON=$(PYTHON) not found in $(PATH)")
endif

PYTHON_VERSION_MIN=3.5
PYTHON_VERSION=$(shell $(PYTHON) -c 'import sys; print("%d.%d"% sys.version_info[0:2])' )
PYTHON_VERSION_OK=$(shell $(PYTHON) -c 'import sys;\
  print(int(float("%d.%d"% sys.version_info[0:2]) >= $(PYTHON_VERSION_MIN)))' )

ifeq ($(PYTHON_VERSION_OK),0)
  $(error "Need python $(PYTHON_VERSION) >= $(PYTHON_VERSION_MIN)")
endif

3
PYTHON=$(shell which python ) - hailinzeng

0
这可能会有所帮助:这里是一个关于在SF上检查Python版本以控制新语言功能的线程。

在这种情况下,请查看此处:http://old.nabble.com/Detecting-which-Python-version-is-used-by-SIP-and-PyQt-td30033430.html - Please treat your mods well.

0
PYTHON=$(shell command -v python3)

ifeq (, $(PYTHON))
    $(error "PYTHON=$(PYTHON) not found in $(PATH)")
endif

PYTHON_VERSION_MIN=3.9
PYTHON_VERSION_CUR=$(shell $(PYTHON) -c 'import sys; print("%d.%d"% sys.version_info[0:2])')
PYTHON_VERSION_OK=$(shell $(PYTHON) -c 'import sys; cur_ver = sys.version_info[0:2]; min_ver = tuple(map(int, "$(PYTHON_VERSION_MIN)".split("."))); print(int(cur_ver >= min_ver))')
ifeq ($(PYTHON_VERSION_OK), 0)
    $(error "Need python version >= $(PYTHON_VERSION_MIN). Current version is $(PYTHON_VERSION_CUR)")
endif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接