【问题标题】:How to capture standard output of a shell command in elisp?如何在 elisp 中捕获 shell 命令的标准输出?
【发布时间】:2011-06-28 04:57:42
【问题描述】:

我想在 Emacs 中运行一个 shell 命令并将完整的输出捕获到一个变量中。有没有办法做到这一点?例如,我希望能够通过以下方式将hello-string 设置为"hello"

(setq hello-string (capture-stdout-of-shell-command "/bin/echo hello"))

函数capture-stdout-of-shell-command是否存在,如果存在,它的真实名称是什么?

【问题讨论】:

    标签: emacs elisp stdout capture


    【解决方案1】:

    shell-command-to-string 是否符合您的目的?
    例如:

    (shell-command-to-string "/bin/echo hello")
    

    希望这会有所帮助。

    【讨论】:

    • 请注意shell-command-to-string 捕获stdout stderr。幸运的是,我们可以将标准错误通过管道传输到 /dev/null:(shell-command-to-string "/bin/echo hello 2>/dev/null")
    【解决方案2】:

    我有一个建议可以扩展伊势紫藤的回答。尝试使用这样的东西:

    (setq my_shell_output
      (substring 
        (shell-command-to-string "/bin/echo hello") 
       0 -1))
    

    这应该将字符串"hello" 设置为my_shell_output 的值,但要干净。使用 (substring) 消除了在 emacs 调用 shell 命令时往往会出现的尾随 \n。它在 Windows 上运行的 emacs 中困扰着我,并且可能也发生在其他平台上。

    【讨论】:

    • 我注意到 emacs 在 Mac OS X 和 Linux 上都这样做了,所以不仅仅是 NTEmacs。
    • (defun my-shell-command-to-string (&rest cmd) (replace-regexp-in-string "\r?\n$" "" (shell-command-to-string (mapconcat 'identity cmd " "))))
    • @spacebat 你想要\\',而不是$
    • echo hellohello\n
    • 在 linux/osx 中,您可以使用 -n 停止输出尾随换行符。例如echo -n hello
    猜你喜欢
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多