Dyllon Gagnier
Dyllon Gagnier

Reputation: 381

How do you get a runtime path for the current file in Racket?

Suppose I have a file called "test.rkt" for which I want to have its absolute path available at runtime. I know that the best way to do this is to bind it using:

(define-runtime-path orig-file "test.rkt")

However, for reflection purposes, I would like to be able to do this without knowing the name of the current file. For example, I would like to be able to do something like:

(define-runtime-path-self orig-file)

Upvotes: 2

Views: 309

Answers (2)

Ryan Culpepper
Ryan Culpepper

Reputation: 10653

You can use #%variable-reference, which (IIRC) is the low-level reflective magic behind define-runtime-path:

(resolved-module-path-name
 (variable-reference->resolved-module-path
  (#%variable-reference)))

There's also the syntax/location library:

(require syntax/location)
(quote-source-file)

but beware that if you compile the file in one location and then move source file and compiled/ directory to another location, the program will print the location where it was compiled, not where it was run.


There's also a way that goes through syntax objects and module-path-indexes, but that's more complicated.

Upvotes: 5

Sorawee Porncharoenwase
Sorawee Porncharoenwase

Reputation: 6502

Does (find-system-path 'run-file) or (simple-form-path (find-system-path 'run-file)) work for you?

Upvotes: 1

Related Questions