第 3 部分 · 应用开发实战
CLI 工具开发
CLI 工具开发
使用 command-line 库构建专业的命令行工具。
基本命令行解析
#lang racket (require racket/cmdline) (define verbose? (make-parameter #f)) (define output-file (make-parameter "output.txt")) (command-line #:program "mytool" #:once-each [("-v" "--verbose") "Show verbose output" (verbose? #t)] #:once-any [("-o" "--output") file "Output file" (output-file file)] #:args (input) (printf "Processing ~a → ~a~n" input (output-file)))
子命令
(define mode (make-parameter #f)) (command-line #:program "todo" #:usage-help "A simple todo list manager" #:handlers (list (handler "add" "Add a new task" (lambda () (mode 'add)) '("task")) (handler "list" "List all tasks" (lambda () (mode 'list)) '()) (handler "done" "Mark task as done" (lambda () (mode 'done)) '("id"))) #:args () (case (mode) [(add) ...] [(list) ...] [(done) ...]))
打包为可执行文件
# 创建可执行文件
raco exe my-tool.rkt
# 生成分发目录(包含 Racket 运行时)
raco dist my-tool-dist my-tool.exe
使用 raco 作为命令入口
你可以让你的工具通过 raco 调用:
raco mytool --verbose input.txt
需要在包中配置 raco 命令:
;; info.rkt #lang info (define raco-commands '(("mytool" (submod mytool main) "My awesome tool" #f)))
小结
Racket 的 command-line 库让你轻松构建专业的 CLI 工具。结合 raco exe 和 raco dist,可以快速分发。