scheme-scripts.texi 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @page
  7. @node Guile Scripting
  8. @section Guile Scripting
  9. Like AWK, Perl, or any shell, Guile can interpret script files. A Guile
  10. script is simply a file of Scheme code with some extra information at
  11. the beginning which tells the operating system how to invoke Guile, and
  12. then tells Guile how to handle the Scheme code.
  13. @menu
  14. * The Top of a Script File:: How to start a Guile script.
  15. * Invoking Guile:: Command line options understood by Guile.
  16. * The Meta Switch:: Passing complex argument lists to Guile
  17. from shell scripts.
  18. * Command Line Handling:: Accessing the command line from a script.
  19. * Scripting Examples::
  20. @end menu
  21. @node The Top of a Script File
  22. @subsection The Top of a Script File
  23. The first line of a Guile script must tell the operating system to use
  24. Guile to evaluate the script, and then tell Guile how to go about doing
  25. that. Here is the simplest case:
  26. @itemize @bullet
  27. @item
  28. The first two characters of the file must be @samp{#!}.
  29. The operating system interprets this to mean that the rest of the line
  30. is the name of an executable that can interpret the script. Guile,
  31. however, interprets these characters as the beginning of a multi-line
  32. comment, terminated by the characters @samp{!#} on a line by themselves.
  33. (This is an extension to the syntax described in R5RS, added to support
  34. shell scripts.)
  35. @item
  36. Immediately after those two characters must come the full pathname to
  37. the Guile interpreter. On most systems, this would be
  38. @samp{/usr/local/bin/guile}.
  39. @item
  40. Then must come a space, followed by a command-line argument to pass to
  41. Guile; this should be @samp{-s}. This switch tells Guile to run a
  42. script, instead of soliciting the user for input from the terminal.
  43. There are more elaborate things one can do here; see @ref{The Meta
  44. Switch}.
  45. @item
  46. Follow this with a newline.
  47. @item
  48. The second line of the script should contain only the characters
  49. @samp{!#} --- just like the top of the file, but reversed. The
  50. operating system never reads this far, but Guile treats this as the end
  51. of the comment begun on the first line by the @samp{#!} characters.
  52. @item
  53. The rest of the file should be a Scheme program.
  54. @end itemize
  55. Guile reads the program, evaluating expressions in the order that they
  56. appear. Upon reaching the end of the file, Guile exits.
  57. @node Invoking Guile
  58. @subsection Invoking Guile
  59. @cindex invocation
  60. Here we describe Guile's command-line processing in detail. Guile
  61. processes its arguments from left to right, recognizing the switches
  62. described below. For examples, see @ref{Scripting Examples}.
  63. @table @code
  64. @item -s @var{script} @var{arg...}
  65. Read and evaluate Scheme source code from the file @var{script}, as the
  66. @code{load} function would. After loading @var{script}, exit. Any
  67. command-line arguments @var{arg...} following @var{script} become the
  68. script's arguments; the @code{command-line} function returns a list of
  69. strings of the form @code{(@var{script} @var{arg...})}.
  70. @item -c @var{expr} @var{arg...}
  71. Evaluate @var{expr} as Scheme code, and then exit. Any command-line
  72. arguments @var{arg...} following @var{expr} become command-line arguments; the
  73. @code{command-line} function returns a list of strings of the form
  74. @code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
  75. Guile executable.
  76. @item -- @var{arg...}
  77. Run interactively, prompting the user for expressions and evaluating
  78. them. Any command-line arguments @var{arg...} following the @code{--}
  79. become command-line arguments for the interactive session; the
  80. @code{command-line} function returns a list of strings of the form
  81. @code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
  82. Guile executable.
  83. @item -L @var{directory}
  84. Add @var{directory} to the front of Guile's module load path. The
  85. given directories are searched in the order given on the command line
  86. and before any directories in the GUILE_LOAD_PATH environment
  87. variable. Paths added here are @emph{not} in effect during execution
  88. of the user's @file{.guile} file.
  89. @item -l @var{file}
  90. Load Scheme source code from @var{file}, and continue processing the
  91. command line.
  92. @item -e @var{function}
  93. Make @var{function} the @dfn{entry point} of the script. After loading
  94. the script file (with @code{-s}) or evaluating the expression (with
  95. @code{-c}), apply @var{function} to a list containing the program name
  96. and the command-line arguments --- the list provided by the
  97. @code{command-line} function.
  98. A @code{-e} switch can appear anywhere in the argument list, but Guile
  99. always invokes the @var{function} as the @emph{last} action it performs.
  100. This is weird, but because of the way script invocation works under
  101. POSIX, the @code{-s} option must always come last in the list.
  102. The @var{function} is most often a simple symbol that names a function
  103. that is defined in the script. It can also be of the form @code{(@@
  104. @var{module-name} @var{symbol})} and in that case, the symbol is
  105. looked up in the module named @var{module-name}.
  106. For compatibility with some versions of Guile 1.4, you can also use the
  107. form @code{(symbol ...)} (that is, a list of only symbols that doesn't
  108. start with @code{@@}), which is equivalent to @code{(@@ (symbol ...)
  109. main)}, or @code{(symbol ...) symbol} (that is, a list of only symbols
  110. followed by a symbol), which is equivalent to @code{(@@ (symbol ...)
  111. symbol)}. We recommend to use the equivalent forms directly since they
  112. corresponf to the @code{(@@ ...)} read syntax that can be used in
  113. normal code, @xref{Using Guile Modules}.
  114. @xref{Scripting Examples}.
  115. @item -ds
  116. Treat a final @code{-s} option as if it occurred at this point in the
  117. command line; load the script here.
  118. This switch is necessary because, although the POSIX script invocation
  119. mechanism effectively requires the @code{-s} option to appear last, the
  120. programmer may well want to run the script before other actions
  121. requested on the command line. For examples, see @ref{Scripting
  122. Examples}.
  123. @item \
  124. Read more command-line arguments, starting from the second line of the
  125. script file. @xref{The Meta Switch}.
  126. @item --emacs
  127. Assume Guile is running as an inferior process of Emacs, and use a
  128. special protocol to communicate with Emacs's Guile interaction mode.
  129. This switch sets the global variable use-emacs-interface to @code{#t}.
  130. This switch is still experimental.
  131. @item --use-srfi=@var{list}
  132. The option @code{--use-srfi} expects a comma-separated list of numbers,
  133. each representing a SRFI number to be loaded into the interpreter
  134. before starting evaluating a script file or the REPL. Additionally,
  135. the feature identifier for the loaded SRFIs is recognized by
  136. `cond-expand' when using this option.
  137. @example
  138. guile --use-srfi=8,13
  139. @end example
  140. @item --debug
  141. Start with the debugging evaluator and enable backtraces. Using the
  142. debugging evaluator will give you better error messages but it will
  143. slow down execution. By default, the debugging evaluator is only used
  144. when entering an interactive session. When executing a script with
  145. @code{-s} or @code{-c}, the normal, faster evaluator is used by default.
  146. @vnew{1.8}
  147. @item --no-debug
  148. Do not use the debugging evaluator, even when entering an interactive
  149. session.
  150. @item -h@r{, }--help
  151. Display help on invoking Guile, and then exit.
  152. @item -v@r{, }--version
  153. Display the current version of Guile, and then exit.
  154. @end table
  155. @node The Meta Switch
  156. @subsection The Meta Switch
  157. Guile's command-line switches allow the programmer to describe
  158. reasonably complicated actions in scripts. Unfortunately, the POSIX
  159. script invocation mechanism only allows one argument to appear on the
  160. @samp{#!} line after the path to the Guile executable, and imposes
  161. arbitrary limits on that argument's length. Suppose you wrote a script
  162. starting like this:
  163. @example
  164. #!/usr/local/bin/guile -e main -s
  165. !#
  166. (define (main args)
  167. (map (lambda (arg) (display arg) (display " "))
  168. (cdr args))
  169. (newline))
  170. @end example
  171. The intended meaning is clear: load the file, and then call @code{main}
  172. on the command-line arguments. However, the system will treat
  173. everything after the Guile path as a single argument --- the string
  174. @code{"-e main -s"} --- which is not what we want.
  175. As a workaround, the meta switch @code{\} allows the Guile programmer to
  176. specify an arbitrary number of options without patching the kernel. If
  177. the first argument to Guile is @code{\}, Guile will open the script file
  178. whose name follows the @code{\}, parse arguments starting from the
  179. file's second line (according to rules described below), and substitute
  180. them for the @code{\} switch.
  181. Working in concert with the meta switch, Guile treats the characters
  182. @samp{#!} as the beginning of a comment which extends through the next
  183. line containing only the characters @samp{!#}. This sort of comment may
  184. appear anywhere in a Guile program, but it is most useful at the top of
  185. a file, meshing magically with the POSIX script invocation mechanism.
  186. Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
  187. @example
  188. #!/usr/local/bin/guile \
  189. -e main -s
  190. !#
  191. (define (main args)
  192. (map (lambda (arg) (display arg) (display " "))
  193. (cdr args))
  194. (newline))
  195. @end example
  196. Suppose a user invokes this script as follows:
  197. @example
  198. $ /u/jimb/ekko a b c
  199. @end example
  200. Here's what happens:
  201. @itemize @bullet
  202. @item
  203. the operating system recognizes the @samp{#!} token at the top of the
  204. file, and rewrites the command line to:
  205. @example
  206. /usr/local/bin/guile \ /u/jimb/ekko a b c
  207. @end example
  208. This is the usual behavior, prescribed by POSIX.
  209. @item
  210. When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
  211. @file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
  212. and @code{-s} from it, and substitutes them for the @code{\} switch.
  213. Thus, Guile's command line now reads:
  214. @example
  215. /usr/local/bin/guile -e main -s /u/jimb/ekko a b c
  216. @end example
  217. @item
  218. Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
  219. file of Scheme code (treating the first three lines as a comment), and
  220. then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
  221. @end itemize
  222. When Guile sees the meta switch @code{\}, it parses command-line
  223. argument from the script file according to the following rules:
  224. @itemize @bullet
  225. @item
  226. Each space character terminates an argument. This means that two
  227. spaces in a row introduce an argument @code{""}.
  228. @item
  229. The tab character is not permitted (unless you quote it with the
  230. backslash character, as described below), to avoid confusion.
  231. @item
  232. The newline character terminates the sequence of arguments, and will
  233. also terminate a final non-empty argument. (However, a newline
  234. following a space will not introduce a final empty-string argument;
  235. it only terminates the argument list.)
  236. @item
  237. The backslash character is the escape character. It escapes backslash,
  238. space, tab, and newline. The ANSI C escape sequences like @code{\n} and
  239. @code{\t} are also supported. These produce argument constituents; the
  240. two-character combination @code{\n} doesn't act like a terminating
  241. newline. The escape sequence @code{\@var{NNN}} for exactly three octal
  242. digits reads as the character whose ASCII code is @var{NNN}. As above,
  243. characters produced this way are argument constituents. Backslash
  244. followed by other characters is not allowed.
  245. @end itemize
  246. @node Command Line Handling
  247. @subsection Command Line Handling
  248. @c This section was written and contributed by Martin Grabmueller.
  249. The ability to accept and handle command line arguments is very
  250. important when writing Guile scripts to solve particular problems, such
  251. as extracting information from text files or interfacing with existing
  252. command line applications. This chapter describes how Guile makes
  253. command line arguments available to a Guile script, and the utilities
  254. that Guile provides to help with the processing of command line
  255. arguments.
  256. When a Guile script is invoked, Guile makes the command line arguments
  257. accessible via the procedure @code{command-line}, which returns the
  258. arguments as a list of strings.
  259. For example, if the script
  260. @example
  261. #! /usr/local/bin/guile -s
  262. !#
  263. (write (command-line))
  264. (newline)
  265. @end example
  266. @noindent
  267. is saved in a file @file{cmdline-test.scm} and invoked using the command
  268. line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
  269. is
  270. @example
  271. ("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
  272. @end example
  273. If the script invocation includes a @code{-e} option, specifying a
  274. procedure to call after loading the script, Guile will call that
  275. procedure with @code{(command-line)} as its argument. So a script that
  276. uses @code{-e} doesn't need to refer explicitly to @code{command-line}
  277. in its code. For example, the script above would have identical
  278. behaviour if it was written instead like this:
  279. @example
  280. #! /usr/local/bin/guile \
  281. -e main -s
  282. !#
  283. (define (main args)
  284. (write args)
  285. (newline))
  286. @end example
  287. (Note the use of the meta switch @code{\} so that the script invocation
  288. can include more than one Guile option: @xref{The Meta Switch}.)
  289. These scripts use the @code{#!} POSIX convention so that they can be
  290. executed using their own file names directly, as in the example command
  291. line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
  292. can also be executed by typing out the implied Guile command line in
  293. full, as in:
  294. @example
  295. $ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
  296. @end example
  297. @noindent
  298. or
  299. @example
  300. $ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
  301. @end example
  302. Even when a script is invoked using this longer form, the arguments that
  303. the script receives are the same as if it had been invoked using the
  304. short form. Guile ensures that the @code{(command-line)} or @code{-e}
  305. arguments are independent of how the script is invoked, by stripping off
  306. the arguments that Guile itself processes.
  307. A script is free to parse and handle its command line arguments in any
  308. way that it chooses. Where the set of possible options and arguments is
  309. complex, however, it can get tricky to extract all the options, check
  310. the validity of given arguments, and so on. This task can be greatly
  311. simplified by taking advantage of the module @code{(ice-9 getopt-long)},
  312. which is distributed with Guile, @xref{getopt-long}.
  313. @node Scripting Examples
  314. @subsection Scripting Examples
  315. To start with, here are some examples of invoking Guile directly:
  316. @table @code
  317. @item guile -- a b c
  318. Run Guile interactively; @code{(command-line)} will return @*
  319. @code{("/usr/local/bin/guile" "a" "b" "c")}.
  320. @item guile -s /u/jimb/ex2 a b c
  321. Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @*
  322. @code{("/u/jimb/ex2" "a" "b" "c")}.
  323. @item guile -c '(write %load-path) (newline)'
  324. Write the value of the variable @code{%load-path}, print a newline,
  325. and exit.
  326. @item guile -e main -s /u/jimb/ex4 foo
  327. Load the file @file{/u/jimb/ex4}, and then call the function
  328. @code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}.
  329. @item guile -l first -ds -l last -s script
  330. Load the files @file{first}, @file{script}, and @file{last}, in that
  331. order. The @code{-ds} switch says when to process the @code{-s}
  332. switch. For a more motivated example, see the scripts below.
  333. @end table
  334. Here is a very simple Guile script:
  335. @example
  336. #!/usr/local/bin/guile -s
  337. !#
  338. (display "Hello, world!")
  339. (newline)
  340. @end example
  341. The first line marks the file as a Guile script. When the user invokes
  342. it, the system runs @file{/usr/local/bin/guile} to interpret the script,
  343. passing @code{-s}, the script's filename, and any arguments given to the
  344. script as command-line arguments. When Guile sees @code{-s
  345. @var{script}}, it loads @var{script}. Thus, running this program
  346. produces the output:
  347. @example
  348. Hello, world!
  349. @end example
  350. Here is a script which prints the factorial of its argument:
  351. @example
  352. #!/usr/local/bin/guile -s
  353. !#
  354. (define (fact n)
  355. (if (zero? n) 1
  356. (* n (fact (- n 1)))))
  357. (display (fact (string->number (cadr (command-line)))))
  358. (newline)
  359. @end example
  360. In action:
  361. @example
  362. $ fact 5
  363. 120
  364. $
  365. @end example
  366. However, suppose we want to use the definition of @code{fact} in this
  367. file from another script. We can't simply @code{load} the script file,
  368. and then use @code{fact}'s definition, because the script will try to
  369. compute and display a factorial when we load it. To avoid this problem,
  370. we might write the script this way:
  371. @example
  372. #!/usr/local/bin/guile \
  373. -e main -s
  374. !#
  375. (define (fact n)
  376. (if (zero? n) 1
  377. (* n (fact (- n 1)))))
  378. (define (main args)
  379. (display (fact (string->number (cadr args))))
  380. (newline))
  381. @end example
  382. This version packages the actions the script should perform in a
  383. function, @code{main}. This allows us to load the file purely for its
  384. definitions, without any extraneous computation taking place. Then we
  385. used the meta switch @code{\} and the entry point switch @code{-e} to
  386. tell Guile to call @code{main} after loading the script.
  387. @example
  388. $ fact 50
  389. 30414093201713378043612608166064768844377641568960512000000000000
  390. @end example
  391. Suppose that we now want to write a script which computes the
  392. @code{choose} function: given a set of @var{m} distinct objects,
  393. @code{(choose @var{n} @var{m})} is the number of distinct subsets
  394. containing @var{n} objects each. It's easy to write @code{choose} given
  395. @code{fact}, so we might write the script this way:
  396. @example
  397. #!/usr/local/bin/guile \
  398. -l fact -e main -s
  399. !#
  400. (define (choose n m)
  401. (/ (fact m) (* (fact (- m n)) (fact n))))
  402. (define (main args)
  403. (let ((n (string->number (cadr args)))
  404. (m (string->number (caddr args))))
  405. (display (choose n m))
  406. (newline)))
  407. @end example
  408. The command-line arguments here tell Guile to first load the file
  409. @file{fact}, and then run the script, with @code{main} as the entry
  410. point. In other words, the @code{choose} script can use definitions
  411. made in the @code{fact} script. Here are some sample runs:
  412. @example
  413. $ choose 0 4
  414. 1
  415. $ choose 1 4
  416. 4
  417. $ choose 2 4
  418. 6
  419. $ choose 3 4
  420. 4
  421. $ choose 4 4
  422. 1
  423. $ choose 50 100
  424. 100891344545564193334812497256
  425. @end example
  426. @c Local Variables:
  427. @c TeX-master: "guile.texi"
  428. @c End: