【问题标题】:Print stdout in Python without shell escape sequences在没有 shell 转义序列的 Python 中打印标准输出
【发布时间】:2016-07-14 19:22:34
【问题描述】:

我正在使用sh 在 Python 脚本中运行 git 命令。

In [1]: from sh import git

In [2]: s = git("log", "-1", pretty="format:%h %s")

In [3]: print s
4f14a66 basic debug page

这似乎按预期工作。但是,在 Django 模板中使用它会得到[?1h= 4f14a66 basic debug page[m [K[?1l>。我尝试使用repr() 查看此字符串中有哪些字符,但无济于事:

In [4]: print repr(s)
4f14a66 basic debug page

原来sh 中的命令返回一个具有.stdout 属性的RunningCommand

In [5]: type(s)
Out[5]: sh.RunningCommand

In [7]: s.stdout
Out[7]: '\x1b[?1h\x1b=\r4f14a66 basic debug page\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'

我如何获得"4f14a66 basic debug page" 即没有转义的字符串?从 Bash 运行命令很好:

$ git log -1 --pretty="format:%h %s"
4f14a66 basic debug page

【问题讨论】:

    标签: python shell escaping sh


    【解决方案1】:

    根据this GitHub issue,正确的解决方法是使用_tty_out=False

    >>> str(git('show', format='%cN', s=True))
    '\x1b[?1h\x1b=\rHonza Javorek\x1b[m\r\n\r\x1b[K\x1b[?1l\x1b>'
    
    >>> str(git('show', format='%cN', s=True, _tty_out=False))
    'Honza Javorek\n'
    

    这也是我重复问题的解决方案:Using sh, git show returns special characters - how to get plain output?

    【讨论】:

      【解决方案2】:

      REPL 中的s.stdout 不会打印它,而是显示它的repr()。使用print s.stdout 获取您要查找的内容。

      如果您不想要任何转义码,请考虑使用subprocess.call() 执行它 - 由于 stdout 不是 tty,大多数程序不会输出任何转义序列。

      【讨论】:

      • 最后,我想在 Django 模板中使用输出。 print 理解转义序列,但我如何剥离它们以获得纯字符串?
      • 啊.. 你在调用 git-log 时尝试过--no-color 吗?
      • 遗憾的是,--no-color 没有变化。
      • subprocess.check_output(["git", "log", "-1", "--pretty=format:%h %s"]) 工作得很好,谢谢。
      猜你喜欢
      • 2015-02-18
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-24
      • 1970-01-01
      • 2017-09-08
      相关资源
      最近更新 更多