简体   繁体   English

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

[英]python sh library, commands with hyphen/dash

The python sh docs say: python sh docs说:

For commands that have dashes in their names, for example /usr/bin/google-chrome, substitute the dash for an underscore: 对于名称中包含破折号的命令,例如/ usr / bin / google-chrome,请将破折号替换为下划线:

I am trying to run the command 我正在尝试运行该命令

git rev-parse --abbrev-ref HEAD

When I try to run the command, git returns an error that I have the wrong command. 当我尝试运行该命令时,git返回错误,指出我的命令错误。 Any way to get around this? 有办法解决这个问题吗?

>>> 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

>>> 

I am unsure as to why it's not working. 我不确定为什么它不起作用。

However, I found that this works instead: 但是,我发现这有效:

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

Leads to: 导致:

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

The substitution rule is only for the command itself -- git -- not for arguments such as 'rev-parse' . 替换规则仅适用于命令本身 - git - 不适用于诸如'rev-parse' This is done because dashes aren't possible in Python function names, but are perfectly possible in options. 这样做是因为在Python函数名称中不可能使用破折号,但在选项中完全可能。

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

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

That said, let's say you used subcommand syntax to pass rev-parse implicitly, like so: 也就是说,假设您使用子命令语法隐式传递rev-parse ,如下所示:

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

The underscore would be appropriate in that case, as you would be prepending the subcommand via a Python token, limited to the usual set of characters (which excludes dashes!) available in that case. 在这种情况下,下划线是合适的,因为您将通过Python令牌添加子命令,仅限于通常的字符集(不包括破折号!)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM