简体   繁体   English

elisp-获取相对于脚本的文件路径

[英]elisp - Get path to file relative to script

Say I am writing an emacs lisp function that interfaces with a file located relative to the file in which the function is defined. 假设我正在编写一个emacs lisp函数,该函数与一个文件相对,该文件相对于定义该函数的文件而定位。

- bin/executable
- foo.el

foo.el : foo.el

(defun foo ()
  (shell-command-to-string
   (format "echo '%s' | ./bin/executable"
           (buffer-substring-no-properties
            (point-min)
            (point-max)))))

If I run this from foo.el then it works great. 如果我从foo.el运行此程序,则效果很好。 If I invoke the function while editing any other file it doesn't work because the path ain't right. 如果我在编辑任何其他文件时调用该函数,则该函数将不起作用,因为路径不正确。

How can I reliably reference ./bin/executable from within foo.el no matter where the function is invoked? 无论在何处调用函数,如何在foo.el可靠地引用./bin/executable

Use load-file-name variable. 使用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))))

You can use a combination of load-file-name and default-directory . 您可以结合使用load-file-namedefault-directory If you only check the former, the file will work if you explicitly load it, but it will not work if you eval it in a buffer. 如果仅检查前者,则该文件在显式加载时将起作用,但如果在缓冲区中进行评估则将不起作用。

For example: 例如:

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

In addition, it might be a good idea to convert the path to an absolute path using expand-file-name . 另外,最好使用expand-file-name将路径转换为绝对路径。

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

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