如何在異步調用期間使用cl-letf
或類似函數覆蓋符號的函數值?我想在呼叫start-process
或start-process-shell-command
後停止顯示緩衝區,而是取而代之取回字符串。使用異步調用覆蓋函數值
下面是一個簡化示例,其中綁定display-buffer
適用於同步版本,但不適用於異步版本。另外,我已經將詞法綁定設置爲true。
(defun tst-fun-sync (url)
(call-process "wget" nil "*wget*" nil url "-O" "-")
(with-current-buffer "*wget*"
(display-buffer (current-buffer))))
(defun tst-fun-async (url)
(set-process-sentinel
(start-process "wget" "*wget*" "wget" url "-O" "-")
#'(lambda (p _m)
(when (zerop (process-exit-status p))
(with-current-buffer (process-buffer p)
(display-buffer (current-buffer)))))))
(defun tst-fun-no-display (fun &rest args)
(cl-letf (((symbol-function 'display-buffer)
#'(lambda (&rest _ignored)
(message "%s" (buffer-string)))))
(apply fun args)))
;; The first has desired result, but not the second
;; (tst-fun-no-display 'tst-fun-sync "http://www.stackoverflow.com")
;; (tst-fun-no-display 'tst-fun-async "http://www.stackoverflow.com")
如何使用'shell-command-to-string'?例如,'(replace-regexp-in-string「\ n」「」(shell-command-to-string「date」))'不需要顯示緩衝區來處理它 - 也就是說,需要在你的例子中使用'display-buffer',我可以看到。 – lawlist
您可能還會對可以以字符串形式捕獲所有進程輸出的進程過濾器感興趣。 https://www.gnu.org/software/emacs/manual/html_node/elisp/Filter-Functions.html – lawlist