How can I check the existence of `expect_out(buffer)` (and related)? - undefined

Debugging a script of mine, I wanted to print expect_out(buffer) (and related, like expect_out(0, string), but occasionally I get this error:
can't read "expect_out(buffer)": no such variable
So I wonder:
Is it possible to check the existence of expect_out(buffer) to avoid that error?
I tried a test like if { $expect_out(0,start) > 0 }, but that failed with a corresponding error message (can't read "expect_out(0,start)": no such variable).

Based on the comment of https://stackoverflow.com/users/13534458/sexpect-expect-for-shells saying
you can use Tcl's info exists varName command.
I replaced
if { $expect_out(0,start) > 0 }
with
if { [info exists expect_out(0,start)] }
and it seems to do the job.

Related

Error: can't rename to "tmp_read_command": command already exists

Consider that you rename command and later you again try to rename that, it would show you this error message.
Error: can't rename to "tmp_read_command": command already exists
What do you do to rename it the first time and not the second time. I mean is there a check condition we can put to find out if a command exists or not.
Details:
Two files:
include.tcl
proc snps_read_command { args } {
echo "Hi, I am there"
eval tmp_read_command
}
proc procedure_a { args } {
rename -force read_command tmp_read_command
rename -force snps_read_comamnd read_command
}
test.tcl
source ./include.tcl
procedure_a
source ./include.tcl
procedure_a
read_command
read_command
Executing above TCL script gives me this error message:
Error: can't rename to "tmp_command": command already exists
This comes because I am calling procedure_a twice. First time, it renames and second time when it tries to rename, it cribs. I understand.
Question is:
What should I write to not do this renaming for second time? I tried info commands tmp_read_command and it did not work out.
is there a check condition we can put to find out if a command exists or not
One of the easiest ways to check is to look at the length of the list returned by info commands with a suitable pattern. Which sounds more complicated than it is for ordinary commands:
if {[llength [info commands tmp_read_command]]} {
puts "The command tmp_read_command already exists"
}
For commands that don't include glob metacharacters in their names (the overwhelming majority of commands!) this becomes a very efficient check at the bytecode level.

How to check if the value of file handle is not null in tcl

I have this snippet in my script:
puts "Enter Filename:"
set file_name [gets stdin]
set fh [open $file_name r]
#Read from the file ....
close $fh
Now, this snippet asks user for a file name.. which is then set as an input file and then read. But when the file with the name $file_name doesn't exists, it shows error saying
illegal file character
How do i check if fh is not null (I don't think there is a concept of NULL in tcl being "everyting is a string" language!), so that if an invalid file_name is given, i can throw a print saying file doesn't exists!
Short answer:
try {
open $file_name
} on ok f {
# do stuff with the open channel using the handle $f
} on error {} {
error {file doesn't exist!}
}
This solution attempts to open the file inside an exception handler. If open is successful, the handler runs the code you give it inside the on ok clause. If open failed, the handler deals with that error by raising a new error with the message you wanted (note that open might actually fail for other reasons as well).
The try command is Tcl 8.6+, for Tcl 8.5 or earlier see the long answer.
Long answer:
Opening a file can fail for several reasons, including missing files or insufficient privileges. Some languages lets the file opening function return a special value indicating failure. Others, including Tcl, signal failure by not letting open return at all but instead raise an exception. In the simplest case, this means that a script can be written without caring about this eventuality:
set f [open nosuchf.ile]
# do stuff with the open channel using the handle $f
# run other code
This script will simply terminate with an error message while executing the open command.
The script doesn't have to terminate because of this. The exception can be intercepted and the code using the file handle be made to execute only if the open command was successful:
if {![catch {open nosuchf.ile} f]} {
# do stuff with the open channel using the handle $f
}
# run other code
(The catch command is a less sophisticated exception handler used in Tcl 8.5 and earlier.)
This script will not terminate prematurely even if open fails, but it will not attempt to use $f either in that case. The "other code" will be run no matter what.
If one wants the "other code" to be aware of whether the open operation failed or succeeded, this construct can be used:
if {![catch {open nosuchf.ile} f]} {
# do stuff with the open channel using the handle $f
# run other code in the knowledge that open succeeded
} else {
# run other code in the knowledge that open failed
}
# run code that doesn't care whether open succeeded or failed
or the state of the variable f can be examined:
catch {open nosuchf.ile} f
if {$f in [file channels $f]} {
# do stuff with the open channel using the handle $f
# run other code in the knowledge that open succeeded
} else {
# run other code in the knowledge that open failed
}
# run code that doesn't care whether open succeeded or failed
(The in operator is in Tcl 8.5+; if you have an earlier version you will need to write the test in another manner. You shouldn't be using earlier versions anyway, since they're not supported.)
This code checks if the value of f is one of the open channels that the interpreter knows about (if it isn't, the value is probably an error message). This is not an elegant solution.
Ensuring the channel is closed
This isn't really related to the question, but a good practice.
try {
open nosuchf.ile
} on ok f {
# do stuff with the open channel using the handle $f
# run other code in the knowledge that open succeeded
} on error {} {
# run other code in the knowledge that open failed
} finally {
catch {chan close $f}
}
# run code that doesn't care whether open succeeded or failed
(The chan command was added in Tcl 8.5 to group several channel-related commands as subcommands. If you're using earlier versions of Tcl, you can just call close without the chan but you will have to roll your own replacement for try ... finally.)
The finally clause ensures that whether or not the file was opened or any error occurred during the execution of the on ok or on error clauses, the channel is guaranteed to be non-existent (destroyed or never created) when we leave the try construct (the variable f will remain with an unusable value, unless we unset it. Since we don't know for sure if it exists, we need to prevent the unset operation from raising errors by using catch {unset f} or unset -nocomplain f. I usually don't bother: if I use the name f again I just set it to a fresh value.).
Documentation: catch, chan, close, error, in operator, file, if, open, set, try, unset
Old answer:
(This answer has its heart in the right place but I'm not satified with it these months later. Since it was accepted and even marked as useful by three people I am loath to delete it, but the answer above is IMHO better.)
If you attempt to open a non-existing file and assign the channel identifier to a variable, an error is raised and the contents of the variable are unchanged. If the variable didn't exist, it won't be created by the set command. So while there is no null value, you can either 1) set the variable to a value you know isn't a channel identifier before opening the file:
set fh {} ;# no channel identifier is the empty string
set fh [open foo.bar]
if {$fh eq {}} {
puts "Nope, file wasn't opened."
}
or 2) unset the variable and test it for existence afterwards (use catch to handle the error that is raised if the variable didn't exist):
catch {unset fh}
set fh [open foo.bar]
if {![info exists fh]} {
puts "Nope, file wasn't opened."
}
If you want to test if a file exists, the easiest way is to use the file exists command:
file exists $file_name
if {![file exists $file_name]} {
puts "No such file"
}
Documentation: catch, file, if, open, puts, set, unset

TCL Checking Environment Variables

So I have been trying to find an answer for this for a bit and could not find the answer on the internet. I need to check to see if an environment variable exists. I thought I had the right code but it keeps returning false.
if { [info exists ::env(USER)] } {
RAT::LogMsg INFO "Found USER"
} else {
RAT::LogMsg INFO "Nope!"
}
Any ideas?
You might want to check what environment variables are actually set; I don't think that USER is one of the guaranteed ones.
RAT::LogMsg INFO "Got these env-vars: [lsort [array names ::env]]"
If puts stdout works in your environment, you can try doing:
parray ::env
(The parray command is a procedure that pretty-prints an array.)
To get the current username reliably, check out the tcl_platform array's user element. That array is generated internally by Tcl (well, with probes to relevant basic OS APIs) instead of by looking at environment variables, and that particular element is always present back at least as far as Tcl 8.4.
RAT::LogMsg INFO "Username is $::tcl_platform(user)"
I've just noticed that the documentation is wrong: it says that the user element comes from USER and/or LOGNAME environment variables. It doesn't, and doesn't in at least 8.5 and 8.6. (And it's definitely my mistake. I forgot to update the code when I fixed this. Ooops!)
You have the right code, test in tclsh:
% if {[info exists ::env(USER)]} {puts "found $::env(USER)"}
found strobel
%
The problem must be in your environment.

exp::winnt_debug parent namespace error

I get the error "can't set "::exp::winnt_debug": parent namespace doesn't exist" when I try to run my expect script using the C implementation of expect interpreter on Windows (expect543.dll).
However the same script works fine if I run it through the ActiveState command tclsh...
The statement "set ::exp::winnt_debug 1" in the script is the cause of the error.
Any idea what might be the reason and how to resolve it?
Please find the code below
package require Expect
set ::exp::winnt_debug 1
set prompt "R4#"
set more " --More--"
expect -timeout 10 "$prompt"
set output [open result.txt "w"]
set running 1
spawn plink -telnet "144.21.12.45" -P 2004
send "enable\r"
send "\r"
send "show running-config\r"
send "\r"
while { $running > 0 } {
expect {
"\n" { puts -nonewline $output "$expect_out(buffer)" }
"$more" {send " "}
"lines *-* " { send " " }
#"$prompt" { set running 0 }
eof { set running 0 }
timeout { set running 0 }
}
}
puts "output is .."
There may be several implementations of Expect for Windows (unlike the Unix version, which has been stable for ages) and it sounds like the details of how they are implemented internally varies quite a bit between them. That's not especially surprising. Furthermore, the variable ::exp::winnt_debug is absolutely internal to a particular implementation.
The immediate fix is to change the line with the error to this:
catch {set ::exp::winnt_debug 1}
Like that, if it fails, it fails silently and won't cause the rest of the program to not run. (Enabling debugging shouldn't make any difference to whether the code runs!)
More generally, either use the ActiveState build (and work out how to package things together in the right way, bearing mind that critical dependency) or stop referring to internal features of it. It's very bad form to be poking your fingers inside the implementation of a package, as nobody ever gave a commitment to support them.

In Tcl, what is the equivalent of "set -e" in bash?

Is there a convenient way to specify in a Tcl script to immediately exit in case any error happens? Anything similar to set -e in bash?
EDIT I'm using a software that implements Tcl as its scripting language. If for example I run the package parseSomeFile fname, if the file fname does't exist, it reports it but the script execution continues. Is there a way that I stop the script there?
It's usually not needed; a command fails by throwing an error which makes the script exit with an informative message if not caught (well, depending on the host program: that's tclsh's behavior). Still, if you need to really exit immediately, you can hurry things along by putting a trace on the global variable that collects error traces:
trace add variable ::errorInfo write {puts stderr $::errorInfo;exit 1;list}
(The list at the end just traps the trace arguments so that they get ignored.)
Doing this is not recommended. Existing Tcl code, including all packages you might be using, assumes that it can catch errors and do something to handle them.
In Tcl, if you run into an error, the script will exit immediately unless you catch it. That means you don't need to specify the like of set -e.
Update
Ideally, parseSomeFile should have return an error, but looks like it does not. If you have control over it, fix it to return an error:
proc parseSomeFile {filename} {
if {![file exists $filename]} {
return -code error "ERROR: $filename does not exists"
}
# Do the parsing
return 1
}
# Demo 1: parse existing file
parseSomeFile foo
# Demo 2: parse non-existing file
parseSomeFile bar
The second option is to check for file existence before calling parseSomeFile.