Ashot
Ashot

Reputation: 10979

How to pass arguments when calling `source` command

I need to run source command from c++ program and pass filename and also some arguments. Is it possible? I want to use them in script like command line arguments (with argc, argv0, ...). http://www.astro.princeton.edu/~rhl/Tcl-Tk_docs/tcl/source.n.html here is not specified how to do it.

Upvotes: 1

Views: 836

Answers (3)

Donal Fellows
Donal Fellows

Reputation: 137687

When doing this from C or C++, you should:

  1. Initialise the Tcl library and create a Tcl interpreter.
  2. Set the global variables argv0, argv and argc to the values expected by a normal Tcl script. This is exactly what tclsh does; the variables are entirely ordinary apart from being initialised this way.
    • argv0 is the name of the “main” script, which might be the script you're about to source.
    • argv is a Tcl list of all the other arguments; argc is the length of that list.
  3. Use Tcl_FSEvalFileEx(interp,pathPtr,encoding) to execute the file; the source command is a very thin wrapper around that call. You probably want to pass the encoding argument as NULL, and the pathPtr argument is a Tcl_Obj reference.

Upvotes: 3

Johannes Kuhn
Johannes Kuhn

Reputation: 15173

If your script accepts the arguments in argv, just set this variable before you source this script.

But if this script calls exit, it will terminate the entire process, usually not what you want. You could use a slave interp to avoid this.

Upvotes: 2

Javide
Javide

Reputation: 2657

There are 3 predefined variables:

$argc - number items of arguments passed to a script.
$argv - list of the arguments.
$argv0 - name of the script.

So in your case, assuming the file sourced is in the same directory and its name is passed as a first argument:

source [lindex $argv 0]

Upvotes: 0

Related Questions