如何以编程方式检查python软件包是否为最新版本? [英] How to check if python package is latest version programmatically?

查看:145
本文介绍了如何以编程方式检查python软件包是否为最新版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在脚本中以编程方式检查软件包的最新版本,并返回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?

推荐答案

快速版本(仅检查软件包)

以下代码使用诸如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

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

以下代码要求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软件包是否为最新版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆