Reputation: 143
I run a .tcl script using a .bat file as per the simplified example below:
script.tcl
set a "this is the script"
puts $a
script.bat
echo off
set tclpath="C:\tclsh.exe"
set filepath="C:\script.tcl"
%tclpath% %filepath%
I wonder whether I can include in the .bat file the commands of the .tcl script, so instead of having two files I just have one .bat file that runs tclsh.exe and passes the commands to the tcl shell.
Is this possible? and how can I do it?
Upvotes: 1
Views: 1006
Reputation: 1478
I wonder whether I can include in the .bat file the commands of the .tcl script, so instead of having two files I just have one .bat file that runs tclsh.exe and passes the commands to the tcl shell.
You can use a CALL to a subroutine in a batch script that will append the commands to the dynamically created script file which you specify with the set filepath
variable.
This way you have everything in the batch script and you do not need to worry about the tcl script file other than ensuring the :tclshScript
routine that creates it has the correct syntax, etc.
You essentially build the tcl script logic with batch ECHO
commands and it'll create it per run.
Use caution with special characters though as the carat ^
symbol may be needed to escape certain character to the tcl script if batch interprets those otherwise or you notice an issue.
echo off
set tclpath="C:\tclsh.exe"
set filepath="C:\script.tcl"
IF EXIST "%filepath%" DEL /Q /F "%filepath%"
CALL :tclshScript
%tclpath% %filepath%
EXIT
:tclshScript
ECHO set a "this is the script">>%filepath%
ECHO puts $a>>%filepath%
GOTO EOF
Upvotes: 1
Reputation: 137557
For many things, there are pages on the Tcler's Wiki that can be looked to for interesting things. In particular, this old page has some really useful techniques. As you read through, you'll see a history of techniques tried. They depend on the fact that Tcl commands can be prefixed with ::
usually (marking them as a weird label in the batch file language) and you can comment out blocks of code in Tcl with if 0
(with Tcl not parsing the contents, beyond ensuring that it is brace-balanced, which code usually is).
The best technique is one that doesn't just make the code multilingual, but also makes it easily readable. Preserving readability is the key to not going crazy.
::if 0 {
@rem This code in here is pure batch script
echo off
set tclpath="C:\tclsh.exe"
%tclpath% "%~f0" %*
@rem Put this at the end; it means terminate since the “eof” label is end-of-file
@goto eof
}
# This code is the pure Tcl code
set a "this is the script"
puts $a
The other bits to be aware of:
"%~f0"
— This gets the full path to the “zero-th argument”, which is the name of the script you're running.%*
— This is all the remaining arguments. It's a good idea to pass them on, and you can access them from Tcl using the list in the global argv
variable.Upvotes: 1