【问题标题】:python sh library, commands with hyphen/dashpython sh 库,带有连字符/破折号的命令
【发布时间】:2015-02-03 21:36:31
【问题描述】:

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

>>> 

【问题讨论】:

  • 就我个人而言,我认为这是一个例子,说明为什么 sh 模块是黑客的集合,与内置 subprocess 模块的更简单行为相比。是的,它们有时是可爱的 hack,并且可以编写更简洁的代码——但如果人们关心正确性,行为应该尽可能明确和明确。

标签: python git sh


【解决方案1】:

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

    但是,我发现这可以代替:

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

    导致:

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

    【讨论】:

    • 你是对的。你的解释比我的更完整。
    • 很抱歉 - 我在这里阅读您的答案作为自我回答,因此“您自己找到了一个答案”,而不是提供信用。已更正。
    • 别担心,没问题:)
    猜你喜欢
    • 1970-01-01
    • 2011-11-26
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多