2

Does OCaml have a way to get the current file/module/script name? Something like:

  • C/C++'s argv[0]
  • Python's sys.argv[0]
  • Perl/Ruby's $0
  • Erlang's ?FILE
  • C#'s ProgramName.Environment.CommandLine
  • Factor's scriptname/script
  • Go's os.Args[0]
  • Haskell's System/getProgName
  • Java's System.getProperty("sun.java.command").split(" ")[0]
  • Node.js's __filename
  • etc.
J. Steen
  • 15,470
  • 15
  • 56
  • 63
mcandre
  • 22,868
  • 20
  • 88
  • 147

4 Answers4

10

I don't know anything about OCaml but some googling turned up

Sys.argv.(0)

See http://caml.inria.fr/pub/docs/manual-ocaml/manual003.html#toc12

Kevin
  • 24,871
  • 19
  • 102
  • 158
3

I presume you are scripting in OCaml. Then Sys.argv.(0) is the easiest way to get the script name. Sys module also provides Sys.executable_name, but its semantics is slightly different:

let _ = prerr_endline Sys.executable_name; Array.iter prerr_endline Sys.argv;;

If I run the above line, putting the line in test.ml, by ocaml test.ml hello world, I have:

/usr/local/bin/ocaml         - executable_name
test.ml                      - argv.(0)
hello                        - argv.(1)
world                        - argv.(2)

So OCaml toplevel does something fancy against argv for you.

In general, obtaining the current module name in OCaml is not easy, from several reasons:

  • ML modules are so flexible that they can be aliased, included into other modules, and applied to module functors.
  • OCaml does not embed the module name into its object file.

One probably possible workaround is to add a variable for the module name by yourself, like:

let ml_source_name = "foobar.ml"

This definition can be probably auto inserted by some pre-processing. However, I am not sure CamlP4 can have the file name of the currently processing source file.

If your main purpose is simple scripting, then of course this pre-processing is too complicated, I am afraid.

camlspotter
  • 8,990
  • 23
  • 27
  • Defining the source name may not work for my purposes. Besides printing the filename for CLI usage purposes, imagine that I want to bundle an API with a CLI. The filename can tell me whether OCaml is loading the code on its own (and therefore should run some main-like function), or whether the code is being loaded by another module, in which it should execute nothing. See http://stackoverflow.com/questions/7604201/scripted-main-in-ocaml/ – mcandre Sep 30 '11 at 16:58
2

In OCaml >= 4.02.0, you can also use __FILE__ to get the filename of the current file, which is similar to Node's __filename and not the same as Sys.argv.(0).

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
1
let _ =
    let program = Sys.argv.(0) in
        print_endline ("Program: " ^ program)

And posted to RosettaCode.

mcandre
  • 22,868
  • 20
  • 88
  • 147