How to get path of current script? - tcl

Sometimes its needed to get current path of a script. What are the ways to do that?

While a script is being evaluated (but not necessarily while its procedures are being called) the current script name (strictly, whatever was passed to source or the C API equivalent, Tcl_EvalFile() and related) is the result of info script; it's highly advisable to normalise that to an absolute pathname so that any calls to cd don't change the interpretation.
Scripts that need the information tend to put something like this inside themselves:
# This is a *good* use of [variable]…
variable myLocation [file normalize [info script]]
They can then retrieve the value (or things derived from it) easily:
proc getResourceDirectory {} {
variable myLocation
return [file dirname $myLocation]
}
The other common locations are:
$::argv0 which is the “main” script (and you're evaluating the main script if it's equal to info script)
[info nameofexecutable] which is the Tcl interpreter program itself (typically the argv[0] at the C level)
[info library] which is where Tcl's own library scripts are located
$::tcl_pkgPath which is a Tcl list of directories where packages are installed
$::auto_path which is a Tcl list of directories where scripts are searched for (including packages! The package path is used to initialise this.)

The best way I found to do that:
set script_path [ file dirname [ file normalize [ info script ] ] ]
puts $script_path

You may also try like this:
file normalize $argv0
file normalize [info nameofexecutable]
to get fully normalized name

You might have a look at http://wiki.tcl.tk/1710. The solution there also takes care of possible (multiple) symbolic links and points to the physical root location of the script.

In case it does not work with "info script", you can do
regsub {/[a-zA-Z0-9_]+$} $argv0 {} path
do $path/other_script_on_the_same_path_as_this.tcl
Now you will have the path of the current script on the variable $path.

Related

Can we create module from shared object ie '*.so' files by renaming it to '$modulename-$version.tm'?

Want to create module from shared object file x.so to avoid load command. Shared object C source code x.c defines package p with version 1 in it.
I renamed x.so to p-1.tm and added its path in ::tcl::tm::path and
used package require p 1
Its showing error that it cannot read command. It is because the main file is x.so instead of x.tcl.
Modules are always sourced. Making them include a loadable library as well requires some trickery. Here's one way. Make a Tcl script like this:
apply {{scriptname realname} {
set script [open $scriptname]
chan configure $script -eofchar \x1a
chan read $script
chan configure $script -translation binary
chan seek $script 1 current; # Reset EOF state and skip past the EOF character
set f [file tempfile filename $realname.so]
chan copy $script $f
chan close $f
chan close $script
tailcall load $filename $realname; # Used to find the _Init function
}} [info script] YourRealLibraryName
Concatenate it with an ASCII EOF char (Ctrl+Z) and then concatenate your real shared library on the end after that, saving it all as the module file. When the script is sourced, it will copy the library off the end of itself into a temporary file and load it from that.
This depends on the fact that source always configures the channel it uses to read the script to use the EOF character to act as an end-of-file marker, even on systems that wouldn't normally use it. You can then read past that and extract any payload data you want from there on. Concatenating a loadable library on the end is trivial, but it needs to be extracted elsewhere to actually be fed into load. Internally, all loading of dynamic libraries in Tcl goes through load; it's the only command that knows how to do it. We're just preparing the way for it (and real files are required by default since we're delegating the actual loading to the operating system library calls that do the job; file tempfile is perfect for this job!). Finally, we wrap everything in an apply and tailcall load at the end so that we clean away all the filename manipulation machinery is cleaned away neatly.
More sophisticated approaches using virtual filesystems are possible, but take far more code to explain. They're still just doing this sort of thing, but with more trickery hidden out of sight.

I need to run tcl script with options from another tcl script

I have a tcl script drakon_gen.tcl . I am running it, from another script run.tcl like this:
source "d:\\del 3\\drakon_editor1.22\\drakon_gen.tcl"
When I run run.tcl I have following output:
This utility generates code from a .drn file.
Usage: tclsh8.5 drakon_gen.tcl <options>
Options:
-in <filename> The input filename.
-out <dir> The output directory. Optional.
Now I need to add to run.tcl options that are in the output. I tried many ways but I receive errors. What is the right way to add options?
When you source a script into a tcl interpreter, you are evaluating the script file in the context of the current interpreter. If it was written to be a standalone program you may run into problems with conflicting variables and procedures in the global namespace. One way to avoid that is to investigate the use of slave interpreters (see the interp command) to provide a separate environment for the child script.
In your specific example it looks like you just need to provide some command line arguments. These are normally provided by the argv variable which holds a list of all the command line arguments. If you define this list before sourcing the script you can feed it the required command line. eg:
set original_argv $argv
set argv [list "--optionname" "value"]
source $additional_script_filename
set argv $original_argv

Wrapped Tcl script stops working when moved

I'm new to Tcl and I have a script that is wrapped using freewrapTCLSH.exe
At first, when started, the program complained about not finding a package
I edited the line the seems to "include" it to
lappend auto_path ../../lib/crc
This worked fine and the .exe started without issues. But then I moved the exe to another folder and it started complaining again. I thought that once the exe was created everything would be done. But it doesn't seem to handle this very well.
At first the entire path to the lib was hard coded into the script and then everything worked fine. But since we can't rely on the exe always being built in the same folder this had to be changed.
Any ideas on how to get around this annoying problem?
../../lib/crc is interpreted using the current working directory each time a package is searched. Having this thing it your ::auto_path is almost always not what you want.
I use [file dirname [info script]] to get a directory of currently sourced Tcl file, adding a relative path to some lib/crc with file join, ensuring to get a full pathname with file normalize. The result of file normalize is what I add to ::auto_path (or remember for future use in some other way):
lappend ::auto_path [file normalize [file join [file dirname [info script]] ../mylib]]
It might be obvious, but still: info script returns the path to file currently being sources, not the path somehow remembered when the file containing a call to it was sourced. If you want to get the current script location, ensure it happens at right time (e.g. do it at top level).
You should deliver the required package (and the dependencies of that package) into your exe.
usually this only involves copying the directory of the required packages to the lib folder in your vfs.

Need some explanation about package in TCL

I am having a little problem understanding the following command:
package ifneeded HelloWorld 1.0 [list source [file join $dir helloworld.tcl]]
in the pkgIndex.tcl,
I understand that when the pkgIndex.tcl is sourced and for example, we package require HelloWorld 1.0 , the helloworld.tcl will be sourced. I dont understand the list command...
The package ifneeded command is used to register (or query) how to make a package actually become present in a Tcl interpreter. This is done by evaluating a script, which is the argument generated with list in your example. Let's deconstruct it.
package ifneeded HelloWorld 1.0 [list source [file join $dir helloworld.tcl]]
---------------- ========== --- =============================================
command name package ver how to make it present,
name result of [list ...]
So far, so good. Now, a little aside: the list command is not just used for making lists, but it also makes guaranteed-substitution-free commands. That is, its result is a scrip that consists of an invocation of the command with its arguments, exactly as they were when they went into the list command.
This means that we're producing a script that is source somefilename, where somefilename is the result of the file join. In other words, you're getting almost the same thing as:
package ifneeded HelloWorld 1.0 "source $dir/helloworld.tcl"
Except that there is no assumption that the filename separator is / (that's formally a feature of the OS, not of Tcl, and file join knows about the difference) and it is safe if $dir happens to contain a space or other metacharacters (rather more common than you might hope).
What is $dir? Well, it's a special feature of pkgIndex.tcl scripts that they are (normally) evaluated in a context that sets the dir variable to the absolute name of the directory that contains the pkgIndex.tcl script. (You mustn't make assumptions about the current directory at this point; that belongs to the user of the main Tcl program, not to the package author.) This makes it enormously easier to relocate a package, as you can place all its component files relative to the one script and just move the whole lot in one chunk.
The package ifneeded command expects the following inputs:
package ifneeded package version ?script?
You can see that in your case, the package is HelloWorld, and the version is 1.0. Finally, the script is [list source [file join $dir helloworld.tcl]]. The reason list is used is that the script parameter expects a list.
The package ifneeded command expects a script as its last argument. A script is expected (in a common sense) to be well-formed, that is, to be parsable by the Tcl parser.
In this case of a rather standard pkgIndex.tcl, the thing to ensure is: no matter what the "dir" variable contains at the time the code from that pkgIndex.tcl is processed, the script should be constructed in such a way, that later the Tcl parser sees in it the source command with exactly one argument — no matter if $dir expanded to contain whitespace or funky characters like { etc.
Enter the list command. Here, it's used to construct a list of two elements: the string "source" and a string containing a file name (to serve as the sole argument to that source command). Now, when that list is interpreted as a script (a string), Tcl ensures that string representation contains all the needed quoting to remove any ambiguity about whitespace etc.
This ensures when the parser later interprets our constructed script, the source command in it will receive exactly one argument.
You can read much more of better written information on using list to prevent quoting issues here.

a question about source in Tcl

I have a file named test7.tcl:
namespace eval ::dai {
variable name "ratzip"
variable birthday "1982"
proc hello {} {
variable name
variable birthday
puts "Hello, I am $name birthday is $birthday"
}
}
and I want to source this file into another file, called test8.tcl in this way:
source test7.tcl
::dai::hello
but it gives me error: couldn't read file "test7.tcl": no such file or directory
but the two files are under the same folder, what happened?
To source a file that is in the same directory as the currently executing script, use this:
source [file join [file dirname [info script]] "test7.tcl"]
Note that this doesn't work inside procedures defined inside the outer script (test8.tcl in your case) because they're typically called after the source finishes. If that's the case for you, the simplest fix is to just save the output of info script in a variable in your outer script (or just source all files immediately instead of lazily for the ultimately best approach).
Use source [file join [file dirname [info script]] test7.tcl] -- that way you'll be sourcing the target file by its full pathname constructed from the full pathname of the file executing source; this will work no matter what your current directory is during the execution.
You don't have to specify the path of the file to be sourced relative to the path of test8.tcl but relative to the current working directory. E.g. use the absolute path:
source /path/to/test7.tcl