Toolserver:Tcl

From mediawiki.org

This page was moved from the Toolserver wiki.
Toolserver has been replaced by Toolforge. As such, the instructions here may no longer work, but may still be of historical interest.
Please help by updating examples, links, template links, etc. If a page is still relevant, move it to a normal title and leave a redirect.

Database Access[edit]

MySQL access is provided by the mysqltcl package.

#!/usr/bin/tclsh
package require mysqltcl

set handle [mysqlconnect -host sql -db u_[exec whoami]]

If you run scripts manually/via cron then mysqltcl uses your .my.cnf directly. If you use mysql inside a web tool, you have to provide the password manually:

#!/usr/bin/tclsh
package require mysqltcl
package require inifile

set password [string trim [ini::value [set ini [ini::open /home/[exec whoami]/.my.cnf r]] client password][ini::close $ini] {"}]
set handle [mysqlconnect -host sql -db u_[exec whoami] -password $password]

FastCGI[edit]

The following example shows how to use Tcl with FastCGI. For HTML output you can use the packages cgi or htmlgen.

#!/usr/bin/tclsh
package require cgi
package require Fcgi

set index 0

while {[FCGI_Accept] >= 0} {
    incr index
    cgi_eval {
        title {Tcl FastCGI cgi example}
        body {
            h1 "Tcl FastCGI cgi example, process #[pid]"
            p "Invocation #$index"
            cgi_parray env
        }
    }
}
#!/usr/bin/tclsh
package require htmlgen
package require Fcgi

namespace import htmlgen::*

set index 0

while {[FCGI_Accept] >= 0} {
    incr index
    puts {Content-type: text/html}
    puts {}
    title - "Tcl FastCGI htmlgen example, process #[pid]"
    body ! {
        p - "Invocation #$index"
        pre + {[parray env]}
    }
}

To prevent MySQL connections from being opened and closed repeatedly inside the while loop, make the database handle variable global:


set handle [mysqlconnect ]
global handle

Installing packages locally[edit]

If you must install packages locally (package is too specialized or you don't want to wait it to be available), you must provide a path to the package location, i.e. the direct parent directory of the directory containing the pkgIndex.tcl file.

Say you installed package foo into ~/foo and write a script in ~/public_html:

#!/usr/bin/tclsh
lappend auto_path ..

package require foo

Category:Programming languages