Py学习  »  Git

在Linux下,使用子进程查询Git状态会引发错误

Carol Eisen • 2 年前 • 366 次点击  

我想用python查询git回购的状态。我正在使用:

subprocess.check_output("[[ -z $(git status -s) ]] && echo 'clean'", shell=True).strip()

这在MacOS上运行良好。然而,在Ubuntu Linux上,我收到一条错误消息:

{CalledProcessError}Command '[[ -z $(git status -s) ]] && echo 'clean'' returned non-zero exit status 127.

我进入同一个文件夹并手动运行

[[ -z $(git status -s) ]] && echo 'clean'

而且效果很好。

我还运行了其他命令,比如

subprocess.check_output("ls", shell=True).strip()

这也很好。

这里出了什么问题?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133688
 
366 次点击  
文章 [ 1 ]  |  最新文章 2 年前
larsks
Reply   •   1 楼
larsks    2 年前

当你设定 shell=True , subprocess 使用 /bin/sh .在Ubuntu上, /垃圾箱/垃圾箱 不是Bash,而是使用特定于Bash的语法( [[...]] ).你可以明确地向 bash 相反:

subprocess.check_output(["/bin/bash", "-c", "[[ -z $(git status -s) ]] && echo 'clean'"]).strip()

但现在还不清楚为什么要在这里使用shell脚本:只需运行 git status -s 使用Python,并自行处理结果:

out = subprocess.run(['git', 'status', '-s'], stdout=subprocess.PIPE)
if not out.stdout:
  print("clean")