How to print a line to STDERR and STDOUT in OCaml?
Posted on In QAIn OCaml, how to print a string as a line to STDOUT? That is, the string and the newline character, nicely?
And similarly, how to print the line to STDERR?
In OCaml, you may print a string with the end line character to STDOUT using the function in the Pervasives module:
val print_endline : string -> unit
Print a string, followed by a newline character, on standard output and flush standard output.
One usage example:
$ ocaml
OCaml version 4.01.1+dev2-2013-12-18+CLOSED
# print_endline "hello world!";;
hello world!
- : unit = ()
#
In OCaml, you can use the Printf.eprintf
function to print to STDERR (which is in Pervasives.stderr
).
Examples:
Use Printf.eprintf
:
$ rlwrap ocaml 2>/tmp/a.txt
OCaml version 4.01.1+dev2-2013-12-18+CLOSED
Cannot find file topfind.
Unknown directive `thread'.
# Printf.eprintf "hello world!";;
- : unit = ()
#
$ cat /tmp/a.txt
hello world!
Use Printf.fprintf
to print to Pervasives.stderr
:
$ rlwrap ocaml 2>/tmp/a.txt
OCaml version 4.01.1+dev2-2013-12-18+CLOSED
Cannot find file topfind.
Unknown directive `thread'.
# Printf.fprintf Pervasives.stderr "hello world!";;
- : unit = ()
#
$ cat /tmp/a.txt
hello world!