[英]elisp - Get path to file relative to script
假設我正在編寫一個emacs lisp函數,該函數與一個文件相對,該文件相對於定義該函數的文件而定位。
- bin/executable
- foo.el
foo.el
:
(defun foo ()
(shell-command-to-string
(format "echo '%s' | ./bin/executable"
(buffer-substring-no-properties
(point-min)
(point-max)))))
如果我從foo.el
運行此程序,則效果很好。 如果我在編輯任何其他文件時調用該函數,則該函數將不起作用,因為路徑不正確。
無論在何處調用函數,如何在foo.el
可靠地引用./bin/executable
?
使用load-file-name
變量。
(defconst directory-of-foo (file-name-directory load-file-name))
(defun foo ()
(shell-command-to-string
(format "echo '%s' | %s"
(buffer-substring-no-properties
(point-min)
(point-max))
(expand-file-name "./bin/executable" directory-of-foo))))
您可以結合使用load-file-name
和default-directory
。 如果僅檢查前者,則該文件在顯式加載時將起作用,但如果在緩沖區中進行評估則將不起作用。
例如:
(defvar my-directory (if load-file-name
;; File is being loaded.
(file-name-directory load-file-name)
;; File is being evaluated using, for example, `eval-buffer'.
default-directory))
另外,最好使用expand-file-name
將路徑轉換為絕對路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.