我在python脚本中使用pip模块来自动安装软件/模块。如何检查(远程)软件/模块是否存在?我在pip模块中找不到允许这样做的东西。
我的代码:
class install_pip:
def __init__(self):
self._liste=['install']
def install(self):
pip.main(self._liste)
def addsoftware(self, software):
if type(software) is str:
self._liste.append(software)
if type(software) is list:
for i in software:
self._liste.append(i)
def delsoftware(self, software):
if type(software) is str:
self._liste.remove(software)
if type(software) is list:
for i in software:
self._liste.remove(i)
def _return(self):
return self._liste[1:len(self._liste)]
list = property(_return)
我想检查'软件'是否存在。 感谢。
编辑:我试过这段代码:
try:
pip.main(['install', 'nonexistentpackage'])
except pip.InstallationError as err:
print(echec)
但我没有得到任何错误......
答案 0 :(得分:1)
我会这样做:
import requests
response = requests.get("http://pypi.python.org/pypi/{}/json"
.format(module_name))
if response.status_code == 200:
# OK, the json document exists so you can
# parse the module details if you want
# by using data = response.json()
#
# anyway, here you know that the module exists!
...
答案 1 :(得分:0)
以下代码将尝试导入包(包类型为' str')。如果它无法导入包(即它没有安装),它将调用Pip并尝试安装包。
import pip
def import_or_install(package):
try:
__import__(package)
print (package, "exists, and was successfully imported.")
except ImportError:
pip.main(['install', package])
import_or_install("name of package")