简体   繁体   English

使用参数从python运行tcl脚本

[英]Running tcl script from python with arguments

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 我正在尝试从python运行tcl脚本,tcl脚本需要执行命令行参数,当我从python中获取tcl文件时,它随后显示错误提示

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. 我已经做过很多搜索,其中大多数都问如何在tcl中将参数传递给python。

python code python代码

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

tcl code tcl代码

puts [lindex $::argv 0]

Is there anyway for me pass python arguments to tcl ? 反正我有将python参数传递给tcl吗?

or 要么

not pass arguments and still compile ? 不传递参数并仍然编译?

since if I compile tcl script only without arguments, it still compiles 因为如果我只编译不带参数的tcl脚本,它仍然会编译

Note: 注意:

In tkinter documentation it says tkinter.Tk is 在tkinter文档中说tkinter.Tk是

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 我试图设置一个全局变量,它在python 3.6下对我有用

The global argv variable is, apart from being set during the startup of a standard Tcl script, not special in any way. 除了在标准Tcl脚本启动期间设置之外,全局argv变量在任何方面都不是特殊的。 You can therefore just set it prior to doing source . 因此,您可以在执行source之前进行设置。 In this case, doing so with lappend in a loop is probably best as it builds the structure of the variable correctly. 在这种情况下, lappend在循环中使用lappend这样做,因为它可以正确构建变量的结构。 There are two other variables that ought to be set as well ( argc and argv0 ); 还应该设置另外两个变量( argcargv0 )。 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. 使用Python的str.format{{{}}}导致将括号括在参数周围,以防止大多数引用问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM