从终端验证是否安装了python 3

时间:2016-07-20 15:58:59

标签: bash python-3.x terminal

我正在编写一个shell脚本,在脚本运行之前,我想验证用户是否安装了Python 3。有没有人知道或有任何关于如何检查它的想法,输出是一个布尔值?

3 个答案:

答案 0 :(得分:14)

交互式shell

只需运行python3 --version。如果安装了Python 3,您应该得到Python 3.7.1之类的输出。

Shell脚本

使用command内置:

if command -v python3 &>/dev/null; then
    echo Python 3 is installed
else
    echo Python 3 is not installed
fi

正如评论中已经提到的那样,请避免使用which,因为它需要启动外部流程,并且可能会在some cases中向您提供错误的输出。

答案 1 :(得分:3)

执行以下命令。 which python3并检查命令$?的退出状态。如果用户安装了python 3,则为0,否则为1。

答案 2 :(得分:1)

您可以在“ python3 -V”输出中使用正则表达式匹配进行检查。

例如:

[[ "$(python3 -V)" =~ "Python 3" ]] && echo "Python 3 is installed"
相关问题