【问题标题】:How can i find the default branch from a list of remote repos in python? [duplicate]我如何从 python 中的远程回购列表中找到默认分支? [复制]
【发布时间】:2023-02-09 22:37:28
【问题描述】:

我需要从命令行传递一个回购列表并检测它们的默认分支。到目前为止,我只找到了返回默认 HEAD git remote show origin | grep 'HEAD' | cut -d':' -f2 | sed -e 's/^ *//g' -e 's/ *$//g' 的命令

但是,我不确定我应该如何在我的代码中执行它。

下面是执行命令python3 app.py testrepo。

下面是代码

@app.route('/test')
def get_default_branch():
    repos = sys.argv[1:]
    origin =repos[0]
    return subprocess.Popen([f"'git', 'remote', 'show', '{origin}''" + "| grep 'HEAD' | cut -d':' -f2 | sed -e 's/^ *//g' -e 's/ *$//g''" ])

【问题讨论】:

标签: python git subprocess


【解决方案1】:

如果您想捕获输出,使用 check_output api 可能更容易

@app.route('/test')
def get_default_branch():
    repos = sys.argv[1:]
    origin =repos[0]
    return subprocess.check_output(
        f"git remote show {origin} | grep 'HEAD' | cut -d':' -f2 | sed -e 's/^ *//g' -e 's/ *$//g'",
        shell=True
    )

https://docs.python.org/3/library/subprocess.html#subprocess.check_output

对于shell=True,还建议使用字符串而不是列表

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2020-11-18
    • 2022-11-12
    • 1970-01-01
    • 2011-04-05
    • 2011-11-19
    • 1970-01-01
    相关资源
    最近更新 更多