Detect python version in shell script

前端 未结 14 2136
清歌不尽
清歌不尽 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

    You could use something along the following lines:

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

    The tuple is documented here. You can expand the Python code above to format the version number in a manner that would suit your requirements, or indeed to perform checks on it.

    You'll need to check $? in your script to handle the case where python is not found.

    P.S. I am using the slightly odd syntax to ensure compatibility with both Python 2.x and 3.x.

提交回复
热议问题