[英]How do I check if an application is installed in windows using Python
我正在嘗試創建一個程序,在 Windows 上安裝一個應用程序(如果尚未安裝)。 我知道可執行文件的文件名,但除此之外一無所知。 我想查詢操作系統以檢查該操作系統上是否安裝了已知名稱或文件名的應用程序。
到目前為止,我只有以下內容:
def IsProgramInstalled(ProgramName):
"""Check whether ProgramName is installed."""
如果有人對此有答案,將不勝感激,因為我在任何地方都找不到。
你可以檢查一個程序是否安裝了shutil:
import shutil
def is_program_installed(program_name):
"""Check whether program_name is installed."""
return shutil.which(program_name)
如果程序已安裝,函數將返回程序的路徑,如果程序未安裝,函數將返回None
。
就我而言,如果我想知道是否安裝了git
,我會得到:
git = is_program_installed("git")
print(git)
# Returns: /usr/bin/git
在 Windows 中,它應該返回如下內容: C:\\Program Files\\Git\\bin\\git.exe
可能會遲到,但我找到了一個基於已安裝程序列表的答案作為關於which
不適用於用戶安裝的程序或不在 PATH 中的程序的答案。
import winreg, win32con
def foo(hive, flag):
aReg = winreg.ConnectRegistry(None, hive)
aKey = winreg.OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", 0, win32con.KEY_READ | flag)
count_subkey = winreg.QueryInfoKey(aKey)[0]
arr = []
for i in range(count_subkey):
try:
asubkey_name = winreg.EnumKey(aKey, i)
asubkey = winreg.OpenKey(aKey, asubkey_name)
arr.append([winreg.QueryValueEx(asubkey, "DisplayName")[0], winreg.QueryValueEx(asubkey, "UninstallString")[0]] )
except EnvironmentError:
continue
return arr
x = foo(win32con.HKEY_LOCAL_MACHINE, win32con.KEY_WOW64_32KEY)
y = foo(win32con.HKEY_LOCAL_MACHINE, win32con.KEY_WOW64_64KEY)
z = foo(win32con.HKEY_CURRENT_USER, 0)
這將為您提供已安裝程序的列表,作為您可以搜索的列表print([x for x in x+y+z if "My Application Name" in x])
但是,這並沒有告訴您它位於何處。
def bar(hive, flag):
aReg = winreg.ConnectRegistry(None, hive)
aKey = winreg.OpenKey(aReg, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\Folders', 0, win32con.KEY_READ | flag)
count_subkey = winreg.QueryInfoKey(aKey)
arr = []
for i in range(count_subkey[1]):
try:
arr.append(winreg.EnumValue(aKey, i)[0])
except EnvironmentError:
continue
return arr
w = bar(win32con.HKEY_LOCAL_MACHINE, win32con.KEY_WOW64_64KEY)
這將為您提供安裝文件夾和子文件夾的列表,您可以通過print('\n'.join(x for x in [x for x in w if "My Application Name" in x]))
正如我嘗試使用 Python Module winapps
的不同方法一樣。 下面的代碼片段。
import winapps
def chk_app_inst(str):
for item in winapps.list_installed():
app_name = str
if app_name in item.name:
get_path = item.install_location
get_uninstall_str = item.uninstall_string
print('App path found:\t', get_path, '\nAlternative Path:\t', get_uninstall_str.replace('uninstall.exe', ''))
所以在使用這段代碼之后,至少我可以通過兩種方式獲取已安裝應用程序的可執行文件。 如果此解決方案可用,請告訴我。
提前致謝,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.