Detect python version in shell script

前端 未结 14 2097
清歌不尽
清歌不尽 2020-12-07 20:26

I\'d like to detect if python is installed on a Linux system and if it is, which python version is installed.

How can I do it? Is there something more graceful than

14条回答
  •  北海茫月
    2020-12-07 21:02

    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 $? (assuming bash), 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.

提交回复
热议问题