Tcl on Windows FAQ (2015-05-09)
Table of Contents
- 1 About this FAQ
- 2 About Tcl
- 2.1 What is Tcl and why should I learn it?
- 2.2 What is Tk ?
- 2.3 What Windows platforms does Tcl support ?
- 2.4 Why should I use Tcl instead of VBScript or PowerShell?
- 2.5 Why should I use Tcl instead of C#/C++/VB.Net
- 2.6 When should I not use Tcl on Windows?
- 2.7 How is Tcl licensed? Can I use it in commercial applications?
- 2.8 Where can I find documentation for Tcl?
- 2.9 Is there a Tcl tutorial?
- 2.10 Where can I get help on Tcl?
- 3 Installing Tcl
- 4 General Usage
- 4.1 What are
tclsh
andwish
? - 4.2 How do I run Tcl in interactive mode?
- 4.3 How do I run a Tcl script from the command line?
- 4.4 How can I associate a Tcl script with the Tcl interpreter application?
- 4.5 How can I invoke a Tcl script from Explorer?
- 4.6 How can I embed a Tcl script in a batch file?
- 4.7 How can I have Tcl always execute a certain set of commands on starting?
- 4.8 When should I use a Tcl extension versus an external program?
- 4.1 What are
- 5 General Windows programming
- 6 Processes
- 6.1 How can I start a new process?
- 6.2 How can I read from and write to a child process?
- 6.3 How can I launch a document or URL?
- 6.4 How can I invoke an action, like print, on a document?
- 6.5 How can I start a privileged process under UAC?
- 6.6 How can I terminate a process?
- 6.7 How can I write a Windows service using Tcl?
- 7 Files and Disks
- 7.1 What file path separator should I in Tcl?
- 7.2 How can I get a list of drives in the system?
- 7.3 How can I access files on remote shares?
- 7.4 How can I monitor changes to the file system?
- 7.5 How can I get device notifications such as CD or pen drive insertion?
- 7.6 How can I access Microsoft structured storage?
- 8 Windows Shell and Desktop
- 9 Interoperating with other applications
- 10 System Administration
- 11 Interoperability with .Net
- 12 Networking and Communications
- 12.1 How can I communicate over the network?
- 12.2 How can I communicate over named pipes and why would I want to?
- 12.3 How can I communicate over serial ports?
- 12.4 How can I download a file or a Web page?
- 12.5 How can I get better networking performance?
- 12.6 How do I secure my connections with SSL/TLS?
- 13 Security
- 14 Building Tcl for Windows
- 15 Tcl packages and extensions
1 About this FAQ
This FAQ is targeted towards using Tcl on Windows. Specifically, it addresses the two most recent releases of Tcl (8.5, 8.6) on Windows 2000 or later. Some examples will not work with older versions of Tcl.
The FAQ does not address general Tcl platform-independent features. Nor does it address questions related to the graphical toolkit Tk.
2 About Tcl
2.1 What is Tcl and why should I learn it?
Tcl is a high-level dynamic language that runs on a wide variety of platforms, from mainstream operating systems like Unix/Linux, Windows and MacOS to embedded systesm like Cisco routers. Code written on one platform will run practically unchanged on another. Tcl's simple but powerful and expressive nature make it suitable for applications ranging from customized systems administration utilities to standalone desktop applications to scalable, distributed servers.
2.2 What is Tk ?
Tk is a toolkit for building cross-platform graphical user interfaces. Although bindings exist for other languages such as Perl and Python, it was originally built as a complement to Tcl and has the tightest binding to that language. Hence, the two are most commonly refered together as Tcl/Tk. This FAQ focuses only on Tcl and does NOT address Tk-related questions.
2.3 What Windows platforms does Tcl support ?
The current release of Tcl, Version 8.6, requires Windows XP or later. The previous release, version 8.5, also supports Windows Windows 2000. Earlier versions of Windows, Windows NT 4.0 and the Windows 98 series, require Tcl 8.4 and are not covered by this FAQ.
2.4 Why should I use Tcl instead of VBScript or PowerShell?
There are several reasons why you might want to use Tcl instead of PowerShell or VBScript for scripting tasks on Windows. First, Tcl deployment is simple, with the option of a single executable distribution that includes your scripts and with no external dependencies. This allows deployment even to systems such as Windows 2008 Server Core which did not support PowerShell due to its dependence on the .NET framework. Second, because of its use of native Windows interfaces, Tcl is lightweight and efficient in use of system resources including CPU, memory and disk. Third, generic scripts such as for XML processing, will run on non-Windows platforms without any modifications.
2.5 Why should I use Tcl instead of C#/C++/VB.Net
Simply put, it's all about minding your P's and Q's:
- Productivity - Tcl's dynamic nature, expressiveness and high level constructs greatly increase programming productivity with shorter development cycles and greater robustness.
- Portability - large portions of your code base, and even entire applications are portable to other platforms with minimal effort.
- Quality - By freeing programmers from low level details Tcl allows them to focus on application logic and architecture. It facilitates incremental development where test case generation fits naturally with writing code.
2.6 When should I not use Tcl on Windows?
There are a few types of applications for which Tcl is not an ideal fit. In particular, applications with sophisticated graphics or printing needs are not good candidates for Tcl. Nevertheless, note Tcl can still be used productively in such applications as the "glue" language that drives and automates the core application engine. For example, Tcl is the de facto standard for scripting in the commercial CAD world even though the core applications are in C++.
2.7 How is Tcl licensed? Can I use it in commercial applications?
Tcl is covered under the very liberal open source BSD license. This means Tcl and its associated libraries can be used in all applications, including commercial ones.
2.8 Where can I find documentation for Tcl?
The reference documentation for all Tcl versions can be downloaded or
browsed on-line at http://www.tcl.tk/man. The ActiveState distribution also
contains a Windows Help CHM file that includes not only the core
documentation but also documentation for various extensions and libraries.
A standalone CHM help file, with similar content, is available from
the TWAPI
download area.
2.9 Is there a Tcl tutorial?
See the online Tcl tutorial. In addition, the Tcler's Wiki provides tutorials, explanations and sample code in all areas. It is also an excellent jump point to the various Tcl resources on the net.
2.10 Where can I get help on Tcl?
You can get questions answered on the comp.lang.tcl newsgroup or the #tcl channel on irc.freenode.net. Commercial support is available from ActiveState.
3 Installing Tcl
3.1 What Tcl distributions are available for Windows?
There are several freely downloadable binary distributions of Tcl available:
- The most commonly used distribution for Tcl is from ActiveState which provides both free and commercially supported editions of their Tcl package for multiple platforms. These distributions include libraries and extensions in addition to the Tcl core.
- The Tcl SourceForge download area contains Tcl distributions for multiple platforms but does not include extensions and libraries.
- The KitCreator site provides customisable Tcl distributions for download which can optionally include other libraries and extensions. The site also provides pre-built executables.
- Builds of daily snapshots are available from Pat Thoyt's site. These are single file executables.
3.2 Are there any single-executable distributions of Tcl?
There are several distributions of Tcl that consist of a single
executable file. These distributions also support binding your
applications scripts within the executable so that your entire
application itself can be distributed as a single executable.
The most commonly used ones are tclkit
and freewrap
. You
can also create your own versions from the KitCreator site.
Pre-built executables are available from
rkeene.org
or the
TWAPI
download area.
4 General Usage
4.1 What are tclsh
and wish
?
Windows distinguishes between console mode and graphical interface programs.
Tcl distributions correspondingly come with two different programs,
tclsh.exe
and wish.exe
. The former is used for scripts that run in
console mode and the latter for applications with a graphical user interface,
generally based on Tk.
Depending on the actual Tcl distribution being used, the executables
may be named differently, for example tclsh86t.exe
and wish86t.exe
.
4.2 How do I run Tcl in interactive mode?
To run the Tcl interpreter, so that you can interactively invoke Tcl commands, simply type in the name of the appropriate executable. This will display a Tcl shell prompt where you can type in commands.
1: c:\> tclsh 2: % puts "Hello world" 3: Hello world 4: % exit 5: c:>
4.3 How do I run a Tcl script from the command line?
To run a console script, invoke the tclsh.exe
program, passing
it the path to the script file. Any additional arguments on the command
line are passed as a list to the script in the argv
global variable.
1: # File printargs.tcl 2: foreach arg $::argv {puts $arg}
We can invoke this script from the command line:
1: c:\> tclsh printargs.tcl first "second arg" 2: first 3: second arg 4: c:\>
4.4 How can I associate a Tcl script with the Tcl interpreter application?
Windows can associate a file with an application so that typing the
name of the file will result in the application being invoked.
During its install, the
ActiveState distribution gives the user the option to associate
files ending in .tcl
with the wish
graphical Tcl shell. If you
are not using this distribution, or you want to associate the .tcl
extension with tclsh
instead, you can change the association from
the File Types
tab in the Folder Options
dialog in Explorer.
In addition, if you want to run the script from the command line simply
by typing its name, add the extension to the PATHEXT
environment
variable.
You may wish to associate separate extensions, for example .tcl
and
.tk
, depending on whether you want the script invoked with tclsh
or wish
.
4.5 How can I invoke a Tcl script from Explorer?
In order to run a Tcl script by double-clicking the script file, the file type must be associated with the Tcl shell. See the previous entry in this FAQ.
4.6 How can I embed a Tcl script in a batch file?
As an alternative to making .tcl
files directly executable, you may
prefer to make scripts executable by embedding them in batch files.
For example, assume printargs.bat
is somewhere in your PATH
and
contains the following:
1: ::if no { 2: @tclsh "%~f0" %* 3: @goto :eof 4: } 5: # Tcl code start 6: 7: foreach arg $argv { puts $arg } 8: # Tcl code end \ 9: :eof
Invoking the file:
1: C:\>printargs first "second arg" 2: first 3: second arg
See an explanation of the above and more sophisticated versions in the Tcl wiki.
4.7 How can I have Tcl always execute a certain set of commands on starting?
On startup, tclsh.exe
reads and executes commands in the file
tclshrc.tl
in the user's home directory. The user's home directory
is given by the environment variable USERPROFILE
or can be displayed
with the Tcl command
% file normalize ~
4.8 When should I use a Tcl extension versus an external program?
Some tasks can be accomplished from Tcl by invoking external programs or through the use of a Tcl extension (example). If you are writing a one-off script with limited use or the command is rarely invoked, using an external program might be sufficient. In other cases, use of an extension is likely to be beneficial. It is generally much faster and also protects against the external program not being available or installed on the target system (this is true even for Windows components) and differences arising from localization.
5 General Windows programming
5.1 How can I access the Windows registry?
Tcl provides the registry
command for doing various operations on
the Windows registry. You will need to load the registry
package
first:
1: % package require registry 2: % registry get HKEY_CURRENT_USER\\Environment PATH 3: c:\bin;c:\tcl\tcl86\bin;c:\msys\bin
5.2 How can I get system information?
The Tcl global array tcl_platform
provides basic information about
the system such as the operating system, version number etc. Additional
information is provided in the Windows environment variables which
can be accessed via the global env
array. For more extensive
details, use the osinfo
module in the TWAPI
extension.
6 Processes
6.1 How can I start a new process?
Tcl provides the exec
command for starting new processes. The command
supports pipes with multiple subprocesses, I/O redirection and background
processes. The following commands all start a copy of notepad:
1: % exec notepad.exe & 2: % exec c:/windows/system32/notepad.exe & 3: % exec {*}[auto_execok notepad] &
Line 1 assumes notepad.exe
is in a directory in your PATH
environment
variable. Line 2 explicitly specifies the path to the program. Line 3
makes use of the auto_execok
command which returns
the full command line required for invocation filling
in the path, extension if missing as well as checking for cmd.exe
built-in commands.
1: % auto_execok notepad 2: C:/WINDOWS/system32/notepad.EXE 3: % auto_execok dir 4: C:/WINDOWS/system32/cmd.exe /c dir
Line 1 returns the path to notepad.exe
. Line 3 returns the
command line to invoke an internal cmd.exe
command.
For additional control over the child process, such as its display
properties, security attributes, priority etc., use the
create_process
command from the TWAPI
extension.
6.2 How can I read from and write to a child process?
Use the Tcl open
command to open a pipe by prefixing the child
process command line with a |
character. Then read and write
using the standard Tcl I/O commands puts
. gets
, read
etc.
1: % set fd [open "| cmd.exe /c dir"] 2: file94e0d8 3: % while {![eof $fd]} {puts [gets $fd]} 4: % close $fd
6.3 How can I launch a document or URL?
To start up an application associated with a file or URL,
invoke the Windows cmd.exe
internal
start
command. For example,
% exec {*}[auto_execok start] "" myfile.doc & % exec {*}[auto_execok start] "" http://www.google.com &
Alternatively, see the next entry.
6.4 How can I invoke an action, like print, on a document?
The Windows Explorer Shell associates certain actions that can
be carried out on a document based on its file type. These actions,
such as Open
, Edit
, Print
can be invoked from the right-click
menu in Explorer. To invoke the action using Tcl, use the
shell_execute
command from the TWAPI
extension.
The following will use the default action Open
to start
editing the file with Microsoft Word.
twapi::shell_execute -path sample.doc
To print the file:
twapi::shell_execute -path sample.doc -verb print
To compose an email message:
twapi::shell_execute -path mailto:[email protected]
6.5 How can I start a privileged process under UAC?
Windows Vista and later versions implement User Account Control (UAC)
under which even processes belonging to privileged accounts run with
reduced privileges unless explicitly elevated by the user.
To start a process in elevated mode, use the
shell_execute
command from the TWAPI
extension with the runas
action.
twapi::shell_execute -verb runas -path services.msc
6.6 How can I terminate a process?
The TWAPI
extension provides the end_process
command for this purpose.
twapi::end_process 1234 foreach pid [twapi::get_process_ids -name notepad.exe] {twapi::end_process $pid}
As an alternative, you can invoke the Windows command line program taskkill.exe
using Tcl's exec
command to terminate a process by its PID or name.
1: exec {*}[auto_execok taskkill] /PID 1234 2: exec {*}[auto_execok taskkill] /IM notepad.exe
6.7 How can I write a Windows service using Tcl?
There are several options for running a Tcl script as a Windows service:
- The
TWAPI
extension'srun_as_service
command. The online book chapter Windows Services provides a detailed guide to writing and managing services usingTWAPI
. - ActiveState's Tcl Development Kit provides a tool to wrap a Tcl script as a Windows service
- Generic programs such as Firedaemon and winserv can also be used
to run a Tcl script as a Windows service by spawning
tclsh.exe
as a child process.
7 Files and Disks
7.1 What file path separator should I in Tcl?
Like the Windows kernel (as opposed to the Windows DOS command prompt),
Tcl will accept either /
or \
as a directory separator in a file path.
However, like in other languages such as C, \
is also used in Tcl syntax
to indicate an escape sequence. Hence when used in a literal it needs
to be doubled:
% file exists c:\\windows\\system32
In some cases, such as executing an external program that expects
\
as the directory separator, you can use the
file nativename
command to convert a path:
% file nativename c:/windows/system32 c:\windows\system32
7.2 How can I get a list of drives in the system?
Use Tcl's file volumes
command.
% file volumes C:/ D:/
7.3 How can I access files on remote shares?
Tcl understands UNC names of the form \\SERVER\SHARE\some\file
so the standard Tcl I/O commands can be used to open and access
files on remote shares.
7.4 How can I monitor changes to the file system?
You can either use the Tcl glob command to read a directory and poll
for changes or use the TWAPI
extension as shown in the session below.
Both methods have their advantages and disadvantages. Polling can be
expensive as the entire directory tree has to be read and compared.
The TWAPI
method uses Windows notification as and when changes
occur and has filtering options. On the other hand, notifications
are not guaranteed to be delivered under load. Reliability is
particularly an issue with remote file systems. You may wish to
use a combination of the two methods depending on the application.
The sample below illustrates use of TWAPI
's
begin_filesystem_monitor
command:
1: % proc pargs args {puts [join $args ,]} 2: % set notifier [twapi::begin_filesystem_monitor C:/windows pargs -subtree true -write true -patterns {*.exe *.dll}] 3: % puts stderr "Type Ctrl-C to exit" 4: % vwait forever
This command will print a line whenever an executable (.exe
or .dll
)
is written to anywhere under the Windows directory. The
vwait
command is required in this small example as notifications
require the Tcl event loop to be running.
7.5 How can I get device notifications such as CD or pen drive insertion?
Use the TWAPI
extension as shown in the session below.
(IMPORTANT: The example assumes the Tcl event loop is running
which is required for receiving notifications.)
1: % proc pargs args {puts "Device event: [join $args ,]"} 2: % set notifier [twapi::start_device_notifier pargs -deviceinterface volume] 3: devnotifier#2 4: Device event: devnotifier#2,devnodes_changed 5: Device event: devnotifier#2,devnodes_changed 6: Device event: devnotifier#2,devicearrival,volume,E:, 7: Device event: devnotifier#2,devnodes_changed 8: Device event: devnotifier#2,deviceremovecomplete,volume,E:, 9: Device event: devnotifier#2,devnodes_changed 10: Device event: devnotifier#2,deviceremovecomplete,volume,D:,mediachange 11: Device event: devnotifier#2,devicearrival,volume,D:,mediachange 12: % ::twapi::stop_device_notifier $notifier
The twapi::start_device_notifier
command on Line 2 is
used to receive notifications
of new volumes including USB pen drives, CD insertion and network shares.
It invokes the supplied callback whenever a device volume change event
occurs. The callback can filter for the events of interest based on
the parameter supplied to it. For example, the above console session
shows the insertion and removal of a USB pen drive (Lines 6 and 8)
followed by the removal and insertion of a new CD (Lines 10 and 11).
The mediachange
attribute
indicates that the event is only a change of CD media as opposed
to a new CD-ROM device.
7.6 How can I access Microsoft structured storage?
The tclstorage
extension
provides access to Microsoft's structured storage format.
8 Windows Shell and Desktop
8.1 How can I create desktop shortcuts?
Use the write_shortcut
command of the TWAPI
extension to create shortcuts.
The code below will create a shortcut on the desktop to notepad.exe
.
1: % set path [file join [::twapi::get_shell_folder desktopdirectory] 2: % twapi::write_shortcut $path -path c:/windows/system32/notepad.exe
For URL shortcuts, use the write_url_shortcut
command from TWAPI
.
8.2 How can I register a hotkey to invoke a script?
Windows hotkeys are a means to invoke actions in an application
irrespective of which application has the keyboard focus. Run the
example below in a DOS window. Ctrl-Alt-F11
will start a copy
of notepad
no matter which application has the foreground.
Ctrl-Alt-F12
will stop the script.
1: set notepad_hk "Ctrl-Alt-F11" 2: set exit_hk "Ctrl-Alt-F12" 3: puts "$notepad_hk will bring up a new copy of notepad" 4: puts "$exit_hk will unregister the hotkey and exit" 5: 6: proc remove_hotkeys_and_exit {} { 7: twapi::unregister_hotkey $::notepad_hk_id 8: twapi::unregister_hotkey $::exit_hk_id 9: exit 10: } 11: 12: set notepad_hk_id [twapi::register_hotkey Ctrl-Alt-F11 "exec notepad.exe &"] 13: set exit_hk_id [twapi::register_hotkey Ctrl-Alt-F12 "remove_hotkeys_and_exit"] 14: 15: # If running in tclsh, need a vwait to get eventloop running. 16: vwait forever
8.3 How can I play audio files?
The Snack extension is a complete and powerful cross-platform package for audio generation, playback, recording and analysis. See the Snack tutorial for examples.
For very basic needs, TWAPI
has a module that can play WAV
files
and system sounds.
% twapi::play_sound c:/windows/media/chimes.wav
8.4 How can I copy and paste text to the clipboard?
8.5 How can I copy and paste formatted or binary data ?
If data you are copying and pasting is not plain text, use the
read_clipboard
and write_clipboard
commands from TWAPI
.
The example session below gets HTML format data from the clipboard.
1: % twapi::open_clipboard (openclip) 2: % set fmt [::twapi::register_clipboard_format "HTML Format"] (getclipfmt) 3: 49384 4: % twapi::read_clipboard $fmt 5: Version:0.9 6: StartHTML:00000158 7: EndHTML:00000260 8: ...lines not shown... 9: <html><body> 10: <!--StartFragment--><h2><a name="name">Tcl for Windows FAQ</a></h2><!--EndFragment--> 11: </body> 12: </html> 13: % twapi::read_clipboard_text 14: Tcl for Windows FAQ 15: % twapi::close_clipboard
Since HTML format is not a standard predefined clipboard format,
Line 2 of the example first gets the format identifier associated with
it. Note also the difference in results with the read_clipboard
command on Line 4 and the read_clipboard_text
command on Line 13.
9 Interoperating with other applications
9.1 How can Tcl communicate with other applications using DDE?
Tcl's built-in dde package
allows Tcl scripts to act
as a DDE client or server. However, DDE is a legacy technology
and you should use COM interfaces instead wherever possible.
9.2 How can Tcl act as a COM client?
Several extensions support COM client access from Tcl.
- The TCOM extension (32-bit only)
- The Optcl extension (32-bit only)
- The
COM
module of theTWAPI
extension (32- and 64-bit)
The online book chapter
The Component Object Model provides a detailed
guide to using the COM
module from TWAPI
.
9.3 How can Tcl act as a COM server?
All of the above packages can be used to implement COM components.
9.4 How can I automate Internet Explorer with Tcl?
Automation of IE using COM is done by creating an instance using
the PROGID InternetExplorer.Application
and calling methods
on it. You can find documentation on MSDN. Here is an example
using TWAPI
.
1: % set ie [twapi::comobj InternetExplorer.Application] 2: % $ie Visible true 3: % $ie Navigate http://www.tcl.tk 4: % $ie destroy
For a TCOM example, see the Wiki article at http://wiki.tcl.tk/29255.
9.5 How can I integrate with Microsoft Office?
Automation or integration with Office can be accomplished using any of the COM extensions mentioned above. For documentation on the objects and methods exposed by Office, follow the links on the Office developer page.
The CAWT package provides a high level Tcl API over COM to interact with Microsoft Office.
9.6 How can SQL Server and other databases be accessed from Tcl?
The tdbc
package shipped as part of the core Tcl 8.6 distribution
includes drivers for various database implementations as well as an
ODBC connector. In addition to the reference pages in the Tcl
documentation, an online
introduction is
available.
10 System Administration
10.1 How can I manage user accounts?
The TWAPI extension provides several commands related to user and group account management.
1: : % twapi::new_user brad -password jennifer 2: : % twapi::add_user_to_global_group angelina_fans brad 3: : % twapi::set_user_password brad angelina 4: : % twapi::delete_user brad
You can also use the Active Directory interfaces for this purpose.
10.2 How can I access Active Directory with Tcl?
You can work with Active Directory via the LDAP
module in the tcllib
package library, or via the Active Directory Service Interface (ADSI)
through one of the Tcl COM extensions.
10.3 How can I use WMI for system management?
Like ADSI, Windows Management Instrumentation (WMI) also provides a scriptable interface via COM which is documented on the MSDN WMI Reference site.
1: % twapi::comobj_object "winmgmts://./root/cimv2" 2: % $wmi -with { 3: {ExecQuery "select * from Win32_NetworkAdapter"} 4: } -iterate net { 5: puts "[$net DeviceID]:[$net Description]" 6: $net destroy 7: } 8: 1:Broadcom 440x 10/100 Integrated Controller 9: 3:Intel(R) PRO/Wireless 2915ABG Network Connection 10: 3:1394 Net Adapter 11: ...
The online book chapter Windows Management Instrumentation provides a detailed guide to accessing WMI from Tcl. Additional examples are on the TWAPI and WMI wiki page.
10.4 How can I check if an application or hotfix is installed?
The Windows Installer database can be accessed using either WMI or the Windows Installer COM object. Either method requires one of the Tcl COM extensions. The example below checks for a specific hotfix.
1: % set wmi [twapi::comobj_object "winmgmts://./root/cimv2"] 2: ::oo::Obj1233 3: % $wmi -with { 4: {ExecQuery "select * from Win32_QuickFixEngineering where HotFixID='KB2485663'"} 5: } -iterate app { 6: puts "[$app HotFixID]: [$app Description]" 7: } 8: KB2485663: Security Update for Windows XP (KB2485663)
10.5 How can I read and write the event log?
Use the Windows event log
module from the TWAPI
extension.
Here is an example to dump the Application event log to the console:
1: set hevl [twapi::eventlog_open -source Application] 2: # Make translation binary (lf), since records have embedded CR-LF, 3: # we will have to explicitly output CR-LF pairs 4: fconfigure stdout -translation lf 5: # Keep reading record until no more 6: while {[llength [set events [twapi::eventlog_read $hevl]]]} { 7: # print out each record 8: foreach eventrec $events { 9: array set event $eventrec 10: set time [clock format $event(-timewritten) -format "%x %X"] 11: set source $event(-source) 12: set category [twapi::eventlog_format_category $eventrec -width -1] 13: set message [twapi::eventlog_format_message $eventrec -width -1] 14: puts -nonewline "Time: $time\r\nSource: $source\r\nCategory: $category\r\n$message\r\n\r\n" 15: } 16: } 17: twapi::eventlog_close $hevl
11 Interoperability with .Net
11.1 Is there a .NET version of Tcl?
Eagle is an implementation of the Tcl scripting language for the .Net Common Language Runtime (CLR). It is fully interoperable with other .Net languages and components.
11.2 How can I call .NET components from Tcl?
The Garuda extension provides support for calling .Net components from Tcl.
12 Networking and Communications
12.1 How can I communicate over the network?
The Tcl socket
command creates a TCP/IP socket that can be used
with the standard Tcl I/O commands such as read
and puts
.
12.2 How can I communicate over named pipes and why would I want to?
Use TWAPI
's namedpipe_server
or namedpipe_client
commands. These
create a Tcl channel that can be used with the standard Tcl I/O
commands. Named pipes are not advised over wide area network connections
for performance reasons. In local environments, their primary
benefit is that they provide an easy means for access control
and authentication.
12.3 How can I communicate over serial ports?
Tcl's open
command can be used to open a serial port. For example,
set fd [open "COM1:" r+]
For ports with number greater than 9, the UNC syntax must be used
instead, for example \\.\COM10
.
set fd [open "\\\\.\\COM10" r+]
Note the \
is doubled in the command as it is the escape character
in Tcl syntax.
Once open, the standard Tcl I/O commands can be used to read and write to the port.
12.4 How can I download a file or a Web page?
Tcl comes with a standard package http
1: % package require http 2: 2.8.3 3: % set tok [http::geturl http://www.google.com] 4: ::http::1 5: % puts "Status: [http::status $tok]" 6: Status: ok 7: % if {[http::status $tok] eq "ok"} { puts [http::data $tok] } 8: <HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8"> 9: ...more lines... 10: </HTML> 11: % http::cleanup $tok
Packages for other protocols, like FTP, are available in tcllib.
The TclCurl extension provides an interface to the libcurl
library
for many more protocols and options.
12.5 How can I get better networking performance?
Tcl's built in socket
cross-platform implementation is
sufficient for the majority
of applications. In some cases where maximum performance and capacity
is desired, the
iocpsock extension provides an interface based on Windows I/O completion
ports. Except for the socket creation command, the extension is fully
compatible with Tcl's I/O commands so it is even possible to choose
between it and the Tcl socket
command at run time.
13 Security
13.1 How do I control access to a file or other resource?
The twapi_security
module in the TWAPI
extension
implements a complete set of commands for manipulating access control
lists for files and other resources. The
Access Control
section in the online book chapter
Windows Security
describes use of these commands.
Alternatively, you can also use the Tcl `exec` command to run the
cacls.exe
program that is included with Windows passing it
appropriate parameters.
13.2 How do I manage certificates?
The pki
module in tcllib provides portable commands for
certificate creation and validation. The
twapi_crypto
module in the TWAPI
extension also
provides similar functionality as well integration with the
Windows certificate store. The primary advantage of the integration
is automatic updates of root certificates and revocation lists.
14 Building Tcl for Windows
14.1 Where can I get the Tcl source code?
The source code for the public releases of Tcl can be obtained from the SourceForge Tcl download area at http://sourceforge.net/projects/tcl/files/Tcl/. Extract the zip file to wherever you want to do the build. Depending on the tool chain you will use to build Tcl, it is advisable to not have spaces in the path.
To get the current development snapshot of Tcl, you can check out sources
from the Tcl source repository at http://core.tcl.tk with a mirror
at http://mirror1.tcl.tk. It is maintained using a distributed revision control
system called fossil
, binaries for which can be downloaded from
http://www.fossil-scm.org/download.html.
Detailed instructions for working with the Tcl repository
are at http://wiki.tcl.tk/28126.
Note: Do not place the sources in a path that has spaces in it.
Some of the compiler tools have problems with such paths.
If necessary, you can use the DOS subst
command to assign a
drive letter to the path in order to hide the spaces.
14.2 Which compiler should I use to build Tcl ?
There are several tool chain options for building Tcl for Windows.
- Building with Visual C++ 6.0, as opposed to a newer Visual Studio version,
has the advantage that the associated runtime library
msvcrt.dll
is pre-installed on every Windows system and does not have to be shipped with your Tcl distribution. However, the compiler is not free. - Building with the Microsoft SDK compilers requires that the compiler runtimes be redistributed. But the compilers themselves are free.
- Building with the open source MinGW tool chain based on
gcc
also does not require redistributing runtime libraries as it usesmsvcrt.dll
. Setup is a little more complicated. - The compilers in newer versions of Visual Studio are identical to the free SDK compilers so not much is to be gained from using these commercial versions.
14.3 How do I build Tcl using Visual C++?
The file win\makefile.vc
in the win
directory is used to build
Tcl using Microsoft's compilers. The build process automatically
figures out what version of the compiler is being used.
Note Visual C++ 6.0 can only build the 32 bit version of Tcl.
There are several options that can be passed to makefile.vc
. See
the top of the file for instructions. The sample below illustrates
most common usage.
"%ProgramFiles%\Microsoft Visual Studio\VC98\Bin\vcvars32.bat" cd <TCL SOURCE ROOT DIRECTORY>\win nmake -f makefile.vc INSTALLDIR=c:\tcl release nmake -f makefile.vc INSTALLDIR=c:\tcl install
The last step is only necessary to install the binaries on the build system or to create a distribution.
Note this only builds Tcl, and not the Tk library. If you want
to build the Tk library as well, you need the February 2003 version
of the SDK since Visual C++ 6.0 does not contain the required libraries
for theming support. Later versions of the SDK will not do as they are
not compatible with Visual C++ 6.0. The environment has to be
set up so that the SDK headers and libraries appear before the
Visual C++ ones. The following assumes the Tcl and Tk distributions
are side-by-side in directories called tcl
and tk
.
1: "%ProgramFiles%\Microsoft Visual Studio\VC98\Bin\vcvars32.bat" 2: "c:\src\SDK-Feb-2003\setenv" /XP32 /RETAIL 3: cd <TCL SOURCE ROOT DIRECTORY>\win 4: nmake -f makefile.vc INSTALLDIR=c:\tcl release 5: nmake -f makefile.vc INSTALLDIR=c:\tcl install 6: nmake -f makefile.vc TCLDIR=..\..\tcl INSTALLDIR=c:\tcl release 7: nmake -f makefile.vc TCLDIR=..\..\tcl INSTALLDIR=c:\tcl install
14.4 How do I build Tcl using the free Windows SDK compiler?
The procedure for building using the Windows SDK compilers is similar to that for Visual C++ 6.0. See that entry for an overview. The procedure below is specified for Windows SDK 7.0 but will be similar for other SDK versions.
First, start a DOS command window to set up the build environment.
Note certain cmd.exe
command extensions have to be enabled
for the SDK setup command file. Therefore, either start the command
shell from the Start->All Programs->Microsoft Windows SDK v7.0->CMD shell
menu or at the DOS command prompt, start a new shell by typing
C:\WINDOWS\system32\cmd.exe /E:ON /V:ON /T:0E
Then, at the command shell prompt, type the following to build 32-bit Tcl:
"%ProgramFiles%\Microsoft SDKs\Windows\v7.0\bin\setenv" /x86 /xp /Release
Alternatively, for 64-bit Tcl, set up for a 64-bit tool chain:
"%ProgramFiles%\Microsoft SDKs\Windows\v7.0\bin\setenv" /x64 /xp /Release
Then to build Tcl and Tk,
1: cd <TCL SOURCE ROOT DIRECTORY>\win 2: nmake -f makefile.vc INSTALLDIR=c:\tcl release 3: nmake -f makefile.vc INSTALLDIR=c:\tcl install 4: nmake -f makefile.vc TCLDIR=..\..\tcl INSTALLDIR=c:\tcl release 5: nmake -f makefile.vc TCLDIR=..\..\tcl INSTALLDIR=c:\tcl install
This will build 32 or 64-bit Tcl depending on how the environment was set up.
Note this procedure can be used for cross-building 64-bit Tcl from a 32-bit system and vice versa.
15 Tcl packages and extensions
15.1 Tcllib
Tcllib is a collection of cross-platform Tcl packages that cover a large number of areas from text processing, mathematical algorithms, data structures, parsing, data structures, HTML and XML, networking, automata and more. It is available from http://tcllib.sourceforge.net.
15.2 Tcl for Windows API (TWAPI)
The TWAPI extension includes modules that cover a broad cross-section of the Windows API. It is available at http://twapi.sourceforge.net.
15.3 Snack Sound Toolkit
The Snack extension is a complete and powerful cross-platform package for audio generation, playback, recording and analysis. It is available at http://www.speech.kth.se/snack/.
15.4 TCOM
The TCOM extension provides support for both COM client and server access from Tcl. It is available from http://www.vex.net/~cthuang/tcom/. Although stable, it is not under active development and there is no 64-bit version available.
15.5 Optcl
The Optcl extension supports COM client and server access and also support for hosting ActiveX controls. It is available at http://www.patthoyts.tk/programming/optcl3010.zip. Like TCOM, it is not under active development and no 64-bit version is available.
15.6 CAWT
The CAWT (COM Automation With Tcl) package (formerly TcomOffice) provides high level interfaces to Microsoft Office (Excel, Word, Powerpoint), Internet Explorer, Matlab and Google Earth. It is available at http://www.posoft.de/html/extCawt.html.
15.7 iocpsock
The iocpsock extension provides a higher performance socket interface using I/O completion ports. It is available from http://sourceforge.net/projects/iocpsock.
15.8 TkPrint
The TkPrint extension provides commands for printing. It is available at http://pages.videotron.com/cclients/files/tkprint1.1.html.
15.9 Gdi and Printer
The Gdi and Printer extensions contain commands to interface to the Win32 GDI and printing API's.
15.10 Eagle and Garuda
Eagle is an implementation of Tcl for .Net. Garuda is a Tcl extension that supports calling .Net components from Tcl. Both are available from http://eagle.to.
15.11 TclCurl
The TclCurl extension provides a Tcl-callable interface to the libcurl
library for retrieving URL's using many different protocols. It is
available from http://personal.telefonica.terra.es/web/getleft/tclcurl/index.html.
15.12 tclkit
Tclkit is a single-file Tcl executable that also supports binding of application scripts within the executable to allow single-file distribution of applications that can be run directly without installing or unpacking. See http://wiki.tcl.tk/52.
15.13 freewrap
Freewrap is another single-executable distribution option. It is available from http://freewrap.sourceforge.net.