在Python子进程中使用反勾号

2024-09-28 20:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过Python脚本运行这个git命令并获得它的输出:

git diff --name-only mybranch `git merge-base mybranch develop`

该命令的目的是查看自上次与develope合并以来对mybranch所做的更改。在

为此,我使用subprocess.Popen

^{pr2}$

然而,这是行不通的。变量output.communicate()[0]只是给了我一个git用法的打印输出——实际上告诉我输入命令是错误的。在

我看到了一个类似的问题exists here,但它只告诉我使用{},这并没有解决我的问题。在

我还尝试连续运行这两个命令,但这给了我与以前相同的输出。不过,我可能在这一步中遗漏了一些东西。在

如有任何帮助或提示,我们将不胜感激。在


Tags: namegit命令目的脚本onlybasediff
2条回答

在POSIX上,参数列表被传递给/bin/sh -c,也就是说,只有第一个参数被识别为一个shell命令,也就是说,shell运行git而没有任何参数,这就是您看到用法信息的原因。如果要使用shell=True,则应将命令作为字符串传递。来自the ^{} docs

On POSIX with shell=True, the shell defaults to /bin/sh. If args is a string, the string specifies the command to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

在这种情况下,您不需要shell=True。在

#!/usr/bin/env python
from subprocess import check_output

merge_base_output = check_output('git merge-base mybranch develop'.split(), 
                                 universal_newlines=True).strip()
diff_output = check_output('git diff  name-only mybranch'.split() +
                           [merge_base_output])

倒勾子流程

反勾号是一个shell特性,您可能别无选择,只能使用shell=True,但是要传入一个shell命令字符串,而不是一个参数列表

所以对于你的特定命令(假设它首先起作用)

process = subprocess.Popen("git diff  name-only mybranch `git merge-base mybranch develop`", stdout=subprocess.PIPE, shell=True)

注意,当你调用Popen()时,你得到了一个进程,不应该被称为outputIMO

这里有一个简单的例子,可以处理反勾号

^{pr2}$

或者您可以使用$(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'

相关问题 更多 >