12

Since python passed to use version 3 as the default there's a need to handle the version2 code execution with the corret python interpreter. I have a small python2 project where I use make to configure and install python package, so here's my question: How can I determine python's version inside Makefile?

Here's the logic I want to use: if (python.version == 3) python2 some_script.py2 else python3 some_script.py3

Thanks in advance!

5 Answers 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
1
  • To support versions prior to 2.5, I used python -V instead
    – fnokke
    Dec 14, 2012 at 13:50
10

Here is a shorter solution. in top of your makefile write:

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

Then you can use it with $(PYV)

8

Here we check for python version > 3.5 before continuing to run make recipes

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
1
  • 3
    PYTHON=$(shell which python )
    – hailinzeng
    Nov 9, 2020 at 1:29
0

This might help: here's a thread in SF about checking the Python version to control new language features.

1
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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.