IT TIP

쉘 스크립트에서 파이썬 버전 감지

itqueen 2020. 11. 3. 19:36
반응형

쉘 스크립트에서 파이썬 버전 감지


Linux 시스템에 Python이 설치되어 있는지, 설치된 경우 어떤 Python 버전이 설치되어 있는지 감지하고 싶습니다.

어떻게하니? 의 출력을 구문 분석하는 것보다 더 우아한 것이 "python --version"있습니까?


다음 줄을 따라 사용할 수 있습니다.

$ python -c 'import sys; print(sys.version_info[:])'
(2, 6, 5, 'final', 0)

튜플은 여기 에 설명되어 있습니다 . 위의 Python 코드를 확장하여 요구 사항에 맞는 방식으로 버전 번호의 형식을 지정하거나 실제로 검사를 수행 할 수 있습니다.

찾을 수없는 $?경우를 처리하려면 스크립트 를 체크인해야합니다 python.

추신 나는 Python 2.x 및 3.x와의 호환성을 보장하기 위해 약간 이상한 구문을 사용하고 있습니다.


python -c 'import sys; print sys.version_info'

또는 사람이 읽을 수있는 :

python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))'

이것도 사용할 수 있습니다.

pyv="$(python -V 2>&1)"
echo "$pyv"

나는 순수하게 쉘로 작성된 것을 만들기 위해 문자열에서 버전 번호 추출 과 함께 Jahid의 대답을 사용했습니다 . 또한 "Python"이라는 단어가 아닌 버전 번호 만 반환합니다. 문자열이 비어 있으면 Python이 설치되지 않은 것입니다.

version=$(python -V 2>&1 | grep -Po '(?<=Python )(.+)')
if [[ -z "$version" ]]
then
    echo "No Python!" 
fi

최신 버전의 Python을 사용하고 있는지 확인하기 위해 버전 번호를 비교하고 싶다면 다음을 사용하여 버전 번호에서 마침표를 제거합니다. 그런 다음 "2.7.0보다 크고 3.0.0보다 작은 Python 버전을 원합니다."와 같은 정수 연산자를 사용하여 버전을 비교할 수 있습니다. 참조 : http://tldp.org/LDP/abs/html/parameter-substitution.html의 $ {var // Pattern / Replacement}

parsedVersion=$(echo "${version//./}")
if [[ "$parsedVersion" -lt "300" && "$parsedVersion" -gt "270" ]]
then 
    echo "Valid version"
else
    echo "Invalid version"
fi

쉘 스크립트에서 버전을 비교하려는 경우 sys.hexversion을 사용하는 것이 유용 할 수 있습니다.

ret=`python -c 'import sys; print("%i" % (sys.hexversion<0x03000000))'`
if [ $ret -eq 0 ]; then
    echo "we require python version <3"
else 
    echo "python version is <3"
fi

표준 Python 라이브러리의 일부인 플랫폼 모듈사용할 수 있습니다 .

$ python -c 'import platform; print(platform.python_version())'
2.6.9

이 모듈을 사용하면 버전 문자열의 일부만 인쇄 할 수 있습니다 .

$ python -c 'import platform; major, minor, patch = platform.python_version_tuple(); print(major); print(minor); print(patch)'
2
6
9

bash에서이 명령을 사용할 수 있습니다.

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

다음은 해시를 사용하여 Python이 설치되어 있는지 확인하고 버전의 처음 두 주요 번호를 추출하고 최소 버전이 설치되었는지 비교하기 위해 sed를 사용하는 또 다른 솔루션입니다.

if ! hash python; then
    echo "python is not installed"
    exit 1
fi

ver=$(python -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/')
if [ "$ver" -lt "27" ]; then
    echo "This script requires python 2.7 or greater"
    exit 1
fi

Python이 설치되어 있는지 확인하려면 (PATH에있는 것으로 간주) 다음과 같이 간단합니다.

if which python > /dev/null 2>&1;
then
    #Python is installed
else
    #Python is not installed
fi

> /dev/null 2>&1부분은 억제 출력있다.

버전 번호도 얻으려면 :

if which python > /dev/null 2>&1;
then
    #Python is installed
    python_version=`python --version 2>&1 | awk '{print $2}'`
    echo "Python version $python_version is installed."

else
    #Python is not installed
    echo "No Python executable is found."
fi

Python 3.5가 설치된 샘플 출력 : "Python 버전 3.5.0이 설치되었습니다."

Note 1: The awk '{print $2}' part will not work correctly if Python is not installed, so either use inside the check as in the sample above, or use grep as suggested by Sohrab T. Though grep -P uses Perl regexp syntax and might have some portability problems.

Note 2: python --version or python -V might not work with Python versions prior to 2.5. In this case use python -c ... as suggested in other answers.


Adding to the long list of possible solutions, here's a similar one to the accepted answer - except this has a simple version check built into it:

python -c 'import sys; exit(1) if sys.version_info.major < 3 and sys.version_info.minor < 5 else exit(0)'

this will return 0 if python is installed and at least versions 3.5, and return 1 if:

  • Python is not installed
  • Python IS installed, but its version less than version 3.5

To check the value, simply compare $?, as seen in other questions.

Beware that this does not allow checking different versions for Python2 - as the above one-liner will throw an exception in Py2. However, since Python2 is on its way out the door, this shouldn't be a problem.


Detection of python version 2+ or 3+ in a shell script:

# !/bin/bash
ver=$(python -c"import sys; print(sys.version_info.major)")
if [ $ver -eq 2 ]; then
    echo "python version 2"
elif [ $ver -eq 3 ]; then
    echo "python version 3"
else 
    echo "Unknown python version: $ver"
fi

If you need to check if version is at least 'some version', then I prefer solution which doesn't make assumptions about number of digits in version parts.

VERSION=$(python -V 2>&1 | cut -d\  -f 2) # python 2 prints version to stderr
VERSION=(${VERSION//./ }) # make an version parts array 
if [[ ${VERSION[0]} -lt 3 ]] || [[ ${VERSION[0]} -eq 3 && ${VERSION[1] -lt 5 ]] ; then
    echo "Python 3.5+ needed!" 1>&2
    return 1
fi

This would work even with numbering like 2.12.32 or 3.12.0, etc. Inspired by this answer.

참고URL : https://stackoverflow.com/questions/6141581/detect-python-version-in-shell-script

반응형