0

I'm trying to run tcl script from python, tcl script requires command line arguments to execute, when I source the tcl file from python, it then shows the error says

tclsh.eval('source "test.tcl"' )
_tkinter.TclError: can't read "::argv": no such variable

I've done many searches, majority of them asks how to pass arguments to python in tcl.

python code

import tkinter
import sys 
tclsh.eval('source "test.tcl"' )
if __name__ == '__main__':
    print("hi")

tcl code

puts [lindex $::argv 0]

Is there anyway for me pass python arguments to tcl ?

or

not pass arguments and still compile ?

since if I compile tcl script only without arguments, it still compiles

Note:

In tkinter documentation it says tkinter.Tk is

The Tk class is instantiated without arguments

Is there a way to instantiated with arguments ?

Sol:

tclsh.eval('set argv [list]')
tclsh.eval('set argc 0')

I tried to set a global variable and it works for me under python 3.6

whtitefall
  • 631
  • 9
  • 16
  • Check if [this question](https://stackoverflow.com/q/37875115/1578604)'s answers are of any help? – Jerry Sep 12 '19 at 16:44
  • @Jerry Hi, I guess no, that question is passing function arguments to tcl function, I;m trying to pass arguments to tcl command line arguments ... – whtitefall Sep 12 '19 at 17:39

1 Answers1

1

The global argv variable is, apart from being set during the startup of a standard Tcl script, not special in any way. You can therefore just set it prior to doing source. In this case, doing so with lappend in a loop is probably best as it builds the structure of the variable correctly. There are two other variables that ought to be set as well (argc and argv0); overall you do it like this (as a convenient function):

def run_tcl_script(script_name, *args):
    tclsh.eval('set argv0 {{{}}}'.format(script_name))
    tclsh.eval('set argv {}; set argc 0')
    for a in args:
        tclsh.eval('lappend argv {{{}}}; incr argc'.format(a))
    tclsh.eval('source $argv0')

The {{{}}} with Python's str.format results in a single layer of braces being put around the argument, defending against most quoting issues.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215