隐藏 `git ls-remote` 的所有输出

问题描述 投票:0回答:1

你好,我正在编写一个函数来检查给定的 http/https URL,该 URL 是否对应于现有的 git 存储库。我想隐藏来自

git ls-remote
的输出。知道该怎么做吗?

import subprocess

def check_git(url: str) -> bool:
    try:
        ret = subprocess.run(
            ["git", "ls-remote", "-q", "--exit-code", url, "HEAD"],
            check=True,
            timeout=10,
            stdout=subprocess.DEVNULL, 
            stderr=subprocess.STDOUT,
        )
        if ret.returncode != 0:
            return False
        return True
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
        return False

if not check_git("https://github.com/ghost/bar.git"):
    print("\nCould not find repo")

当我运行此程序时,我会收到用户名提示。所以看来子进程重定向在这里不起作用。

python git.py
Username for 'https://github.com':
Could not find repo
python python-3.x git
1个回答
0
投票

回答我自己,

start_new_session=True
,似乎是关键。

import subprocess

def check_git(url: str) -> bool:
    try:
        ret = subprocess.check_call(
            ["git", "ls-remote", "-q", "--exit-code", url, "HEAD"],
            timeout=10,
            start_new_session=True,
            stdout=subprocess.DEVNULL, 
            stderr=subprocess.STDOUT,
        )
        return True
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError):
        return False

if not check_git("https://github.com/GNOME/gnome-shell.git"):
    print("Could not find repo")
else:
    print("Valid repo")
© www.soinside.com 2019 - 2024. All rights reserved.