在我的 python3 软件中,我需要检查是否安装了 git。我知道从终端我可以输入:
dpkg --get-selections > filename
Run Code Online (Sandbox Code Playgroud)
查找安装了哪些程序,然后将其放入文件中。
从那里,我将如何获得 python 以查看是否安装了 git?或者有更简单的方法吗?
你可以使用 python apt 模块,但它只检查包是否安装。如果非 deb 发行版或安装在包管理器之外,它将失败:
import apt
cache = apt.Cache()
cache.open()
cache["git-core"].is_installed# Evaluates true if git is installed
Run Code Online (Sandbox Code Playgroud)
尝试运行 git 并在失败时处理异常:
import subprocess
try:
# pipe output to /dev/null for silence
null = open("/dev/null", "w")
subprocess.Popen("git", stdout=null, stderr=null)
null.close()
except OSError:
print("git not found")
Run Code Online (Sandbox Code Playgroud)
第三种选择是尝试所有路径$PATH并测试您是否对路径/git 具有 exec 权限。
如果你想这样做,你可以这样做:
检查变量 = 0
对于打开的行(“文件名”):
如果“git”在行:
检查变量 = 检查变量 + 1
print "短语 git found ", checkvar, "times"