How to check if a pip package exists in certain given custom index?

Question:

I’ve to check whether a package exists in the given index-url (authenticated) using python script.

For example:

I’ve to check if package package-1 exists in index https://mytestdomain.com/pypi/pypi/simple/

Is there any method to achieve this?

What I’ve tried?

I’ve tried the cli method, like configuring pip.conf with the above index-url and using pip download <package_name>

Asked By: DilLip_Chowdary

||

Answers:

Use subprocess.run with the --no-deps and --dry-run options:

import subprocess, sys

def check_exists(package_name: str, index_url: str = "https://pypi.org/simple") -> bool:
    return not subprocess.run(
        [
            sys.executable,
            "-m",
            "pip",
            "install",
            "--dry-run",
            "--no-deps",
            "--index-url",
            index_url,
            package_namee,
        ],
        capture_output=True,
    ).returncode
Answered By: pigrammer

Here is another solution without pip cli (2x faster than pip cli method).

def check_if_package_exists_in_given_index(package_name_with_version: str, index_url: str) -> bool:
    if "==" in package_name_with_version:
        package_name, version = package_name_with_version.split("==")

        package_url = index_url.strip(
            "/") + f"/{package_name.replace('_', '-')}/{version}/{package_name}-{version}.tar.gz"
    else:
        package_name = package_name_with_version

        package_url = index_url.strip("/") + f"/{package_name.replace('_', '-')}"

    response = requests.get(url=package_url)

    return response.status_code == 200
Answered By: DilLip_Chowdary
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.