I'm new to Racket (and Lisp's in general) and I'm wondering if there's a canonical way to detect if a script was run from the command line?
For example, in Python the standard way to do this would be with if __name__ == __main__:
as so:
def foo():
"foo!"
if __name__ == "__main__":
foo()
Now, suppose I having the following Racket code, and I'd like respond
to be invoked only when this is run as a script.
#lang racket
(require racket/cmdline)
(define hello? (make-parameter #f))
(define goodbye? (make-parameter #f))
(command-line #:program "cmdtest"
#:once-each
[("-H" "--hello") "Add Hello Message" (hello? #t)]
[("-G" "--goodbye") "Add goodbye Message" (goodbye? #t)])
(define (respond)
(printf "~a\n"
(apply string-append
(cond
[(and (hello?) (goodbye?)) '("Hello" " and goodbye.")]
[(and (hello?) (not (goodbye?))) '("Hello." "")]
[(and (not (hello?)) (goodbye?)) '("" "Goodbye.")]
[else '("" "")]))))
Is there an easy/standard way to achieve what I want?
Racket has the concept of main
submodules. You can read about them in the Racket Guide section entitled Main and Test Submodules. They do precisely what you want—when a file is run directly using racket
or DrRacket, the main submodule is executed. If a file is used by another file using require
, the main submodule is not run.
The Racket equivalent of your Python program would be the following:
#lang racket
(define (foo)
"foo!")
(module+ main
(foo))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With