假设我有一个名为“test.rkt”的文件,我希望其绝对路径在运行时可用。我知道最好的方法是使用以下方式绑定它:
(define-runtime-path orig-file "test.rkt")
Run Code Online (Sandbox Code Playgroud)
但是,出于反射目的,我希望能够在不知道当前文件的名称的情况下执行此操作。例如,我希望能够执行以下操作:
(define-runtime-path-self orig-file)
Run Code Online (Sandbox Code Playgroud)
你可以使用#%variable-reference,它(IIRC)是背后的低级反射魔法define-runtime-path:
(resolved-module-path-name
(variable-reference->resolved-module-path
(#%variable-reference)))
Run Code Online (Sandbox Code Playgroud)
还有syntax/location图书馆:
(require syntax/location)
(quote-source-file)
Run Code Online (Sandbox Code Playgroud)
但要注意,如果您在一个位置编译文件,然后将源文件和目录移动到另一个位置,程序将打印编译compiled/的位置,而不是运行的位置。
还有一种方法可以遍历语法对象和模块路径索引,但这更复杂。