scheme-scripts.texi 15 KB

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