我想通过Python脚本运行此git命令并获取其输出:
git diff --name-only mybranch `git merge-base mybranch develop`
该命令的目的是查看自从上次与developer合并以来,在mybranch上进行了哪些更改.
为此,我使用subprocess.Popen:
output = subprocess.Popen(["git", "diff", "--name-only", "mybranch", "`git merge-base mybranch develop`"], stdout=subprocess.PIPE, shell=True)
但是,这不起作用.变量output.communicate()[0]只是给我git用法的打印输出-本质上告诉我输入命令是错误的.
我看到了一个类似的问题exists here,但它只告诉我使用shell = True并不能解决我的问题.
我也尝试连续运行这两个命令,但这给了我与以前相同的输出.不过,我可能在此步骤中缺少了一些东西.
任何帮助或提示,不胜感激.
解决方法:
反引号和子流程
反引号是shell功能,您可能别无选择,只能使用shell = True,但是传入shell命令字符串,而不是args列表
因此,对于您的特定命令(假设它首先起作用)
process = subprocess.Popen("git diff --name-only mybranch `git merge-base mybranch develop`", stdout=subprocess.PIPE, shell=True)
请注意,当您调用Popen()时,您将获得一个进程,不应将其称为输出IMO.
这是一个适用于反引号的简单示例
>>> process = subprocess.Popen('echo `pwd`', stdout=subprocess.PIPE, shell=True)
>>> out, err = process.communicate()
>>> out
'/Users/bakkal\n'
或者您可以使用$(cmd)语法
>>> process = subprocess.Popen('echo $(pwd)', stdout=subprocess.PIPE, shell=True)
>>> out, err = process.communicate()
>>> out
'/Users/bakkal\n'
这是行不通的(对于反引号)
>>> process = subprocess.Popen(['echo', '`pwd`'], stdout=subprocess.PIPE, shell=True)
>>> out, err = process.communicate()
>>> out
'\n'
>>> process = subprocess.Popen(['echo', '`pwd`'], stdout=subprocess.PIPE, shell=False)
>>> out, err = process.communicate()
>>> out
'`pwd`\n'