问题描述
如何在脚本中以编程方式检查包是否为最新版本并返回 true 或 false?
How do you check if a package is at its latest version programmatically in a script and return a true or false?
我可以使用这样的脚本进行检查:
I can check with a script like this:
package='gekko'
import pip
if hasattr(pip, 'main'):
from pip import main as pipmain
else:
from pip._internal import main as pipmain
pipmain(['search','gekko'])
或使用命令行:
(base) C:User>pip search gekko
gekko (0.2.3) - Machine learning and optimization for dynamic systems
INSTALLED: 0.2.3 (latest)
但是我如何以编程方式检查并返回 true 或 false?
But how do I check programmatically and return true or false?
推荐答案
Fast Version (Checking the package only)
下面的代码调用具有不可用版本的包,例如pip install package_name==random
.该调用返回所有可用版本.程序读取最新版本.
Fast Version (Checking the package only)
The code below calls the package with an unavailable version like pip install package_name==random
. The call returns all the available versions. The program reads the latest version.
程序然后运行 pip show package_name
并获取包的当前版本.
The program then runs pip show package_name
and gets the current version of the package.
如果找到匹配项,则返回 True,否则返回 False.
If it finds a match, it returns True, otherwise False.
这是一个可靠的选择,因为它位于 pip
This is a reliable option given that it stands on pip
import subprocess
import sys
def check(name):
latest_version = str(subprocess.run([sys.executable, '-m', 'pip', 'install', '{}==random'.format(name)], capture_output=True, text=True))
latest_version = latest_version[latest_version.find('(from versions:')+15:]
latest_version = latest_version[:latest_version.find(')')]
latest_version = latest_version.replace(' ','').split(',')[-1]
current_version = str(subprocess.run([sys.executable, '-m', 'pip', 'show', '{}'.format(name)], capture_output=True, text=True))
current_version = current_version[current_version.find('Version:')+8:]
current_version = current_version[:current_version.find('\n')].replace(' ','')
if latest_version == current_version:
return True
else:
return False
Edit 2021:下面的代码不再适用于新版本的 pip
以下代码调用pip list --outdated
:
import subprocess
import sys
def check(name):
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'list','--outdated'])
outdated_packages = [r.decode().split('==')[0] for r in reqs.split()]
return name in outdated_packages
这篇关于如何以编程方式检查python包是否是最新版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!