Bryan
Bryan

Reputation: 339

How to output a Tcl procedure into a file

proc my_proc {} {
    puts "Hello World!"
}

How do I output this proc contents to a file? I know 'info body my_proc' can print the contents on the screen. I have tried the following but no luck.

redirect [info body my_proc] > filename.txt

Upvotes: 0

Views: 2644

Answers (2)

glenn jackman
glenn jackman

Reputation: 247192

To be able to (mostly) recreate the proc, try this:

set procname "my_proc"
set procedure [list proc $procname [info args $procname] [info body $procname]]
puts $procedure

I say "mostly" because info args does not emit any default values for the arguments. For that, see https://core.tcl.tk/tips/doc/trunk/tip/65.md that I wrote and abandoned (shockingly) 17 years ago.

Upvotes: 1

mrcalvin
mrcalvin

Reputation: 3434

Simply use [puts]:

set f [open filename.txt w]
puts $f [info body my_proc]
close $f

I know 'info body my_proc' can print the contents on the screen.

[info] is not an I/O command. It serves for introspection and returns the body script ("proc contents") of a Tcl procedure as a string. [puts] then "prints" a given string value to an I/O channel.

Upvotes: 2

Related Questions