我是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 '("" "")]))))
有没有简单/标准的方法来实现我想要的?
Racket具有main
子模块的概念。您可以在“球拍指南”部分的“主模块和测试子模块”中阅读它们。它们恰好可以满足您的需要-当直接使用racket
或DrRacket运行文件时,将执行主子模块。如果一个文件被另一个文件使用require
,则主子模块不会运行。
Python程序的Racket等效项如下:
#lang racket
(define (foo)
"foo!")
(module+ main
(foo))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句