我是Racket(和Lisp的一般)的新手,我想知道是否有一种规范的方法可以检测脚本是否是从命令行运行的?
例如,在Python中,执行此操作的标准方法是使用if __name__ == __main__:
,因为:
def foo():
"foo!"
if __name__ == "__main__":
foo()
现在,假设我有以下的Racket代码,并且只有当它作为脚本运行时我才会调用respond
。
#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 '("" "")]))))
是否有一种简单/标准的方式来实现我想要的目标?
答案 0 :(得分:8)
Racket具有main
子模块的概念。您可以在标题为Main and Test Submodules的“球拍指南”部分中了解它们。它们正是您想要的 - 当使用racket
或DrRacket直接运行文件时,执行主子模块。如果另一个文件使用require
使用文件,则不会运行主子模块。
与Python程序等效的Racket如下:
#lang racket
(define (foo)
"foo!")
(module+ main
(foo))