【问题标题】:Print bash script output in Python在 Python 中打印 bash 脚本输出
【发布时间】:2021-01-11 10:41:27
【问题描述】:

我有一个 Python 代码,它将运行一个脚本文件。脚本文件将输出特定 git 存储库的版本标记。

我的名为“start.sh”的脚本文件如下:

#!/bin/sh
git clone https://xxxxxxxxxx:x-oauth-basic@github.com/xxxxxxx/xxxxx.git
cd xxxxxxxx
git config --global user.email "xxxxxxxx"
git config --global user.name "xxxxxxxxx"
IMAGE_TAG=`echo \`git describe --tags\``
echo $IMAGE_TAG

我的Python代码如下:

import os
git_tag = os.popen('sh start.sh')
print(git_tag)

当我单独运行脚本文件时,它会返回 git 标签。但是,每当我尝试在 Python 代码中打印它时,它都无法正常工作。

我该如何解决这个问题?

【问题讨论】:

标签: python python-3.x bash shell github


【解决方案1】:

对于python3-X

from subprocess
git_tag = subprocess.run(['sh', 'start.sh'], capture_output=True, text=True)
print(git_tag.stdout)

【讨论】:

    【解决方案2】:

    这样试试

    from subprocess import check_output
    out = check_output(['sh', 'start.sh'])
    print(out)
    

    【讨论】:

    • 对于明确标记为 python-3.x 的问题,您不应提供 Python 2 答案。
    【解决方案3】:

    根据python's documentation, os.popen() 函数自 2.6 版以来已被弃用。您可能想使用subprocess 模块。

    P.S:我想发表评论,但不能因此回答。

    【讨论】:

    • 您正在链接到 Python 2 文档。它在 Python 3.x 中的某个时候被恢复,尽管现在它只是 subprocess 的(不必要的)包装器。
    【解决方案4】:

    既然您无论如何都在使用 Python,那么您可以考虑使用 GitPython 作为替代方案。您可以列出所有标签:

    from git import Repo
    repo = Repo("path/to/repo")
    print(repo.tags)
    

    【讨论】:

    • 我有私有的 git hub 存储库。所以,看来我也需要在这个库中添加身份验证机制。
    • 也许看看stackoverflow.com/a/62796479/8505949。我自己还没有验证它,但似乎是一个很好的起点。
    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2013-03-21
    • 2012-08-01
    • 2013-10-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多