python sh库,带连字符/破折号的命令

时间:2014-12-05 16:36:46

标签: python git sh

The python sh docs say:

  

对于名称中包含破折号的命令,例如/ usr / bin / google-chrome,请将破折号替换为下划线:

我正在尝试运行命令

git rev-parse --abbrev-ref HEAD

当我尝试运行该命令时,git会返回错误,指出我的命令错误。有办法解决这个问题吗?

>>> from sh import git
>>> git.rev_parse('--abbrev-ref', 'HEAD')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/sh.py", line 769, in __call__
    return RunningCommand(cmd, call_args, stdin, stdout, stderr)
  File "/Library/Python/2.7/site-packages/sh.py", line 330, in __init__
    self.wait()
  File "/Library/Python/2.7/site-packages/sh.py", line 334, in wait
    self._handle_exit_code(self.process.wait())
  File "/Library/Python/2.7/site-packages/sh.py", line 348, in _handle_exit_code
    self.process.stderr
sh.ErrorReturnCode_1: 

  RAN: '/usr/bin/git rev_parse --abbrev-ref HEAD'

  STDOUT:


  STDERR:
git: 'rev_parse' is not a git command. See 'git --help'.

Did you mean this?
    rev-parse

>>> 

2 个答案:

答案 0 :(得分:3)

我不确定它为什么不起作用。

然而,我发现这有效:

git('rev-parse', '--abrev-ref', 'HEAD')

导致:

RAN: '/usr/bin/git rev-parse --abrev-ref HEAD'

答案 1 :(得分:1)

替换规则仅适用于命令本身 - git - 不适用于'rev-parse'等参数。这样做是因为在Python函数名称中不可能使用破折号,但在选项中完全可能。

@runDOSrun找到了一个解决方案:

git('rev-parse', '--abrev-ref', 'HEAD')

那就是说,让我们假设您使用子命令语法隐式传递rev-parse,如下所示:

git.rev_parse('--abrev-ref', 'HEAD')

在这种情况下,下划线是合适的,因为您将通过Python令牌添加子命令,仅限于通常的字符集(不包括破折号!)。