Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if script executed from command line in Racket?

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?

like image 632
Paul M. Avatar asked Feb 18 '15 18:02

Paul M.


1 Answers

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))
like image 144
Alexis King Avatar answered Sep 26 '22 20:09

Alexis King