Detecting if script executed from command line in Racket?
Asked Answered
R

1

13

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?

Rima answered 18/2, 2015 at 18:52 Comment(0)
S
11

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))
Suziesuzuki answered 18/2, 2015 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.