使用参数从python运行tcl脚本 [英] Running tcl script from python with arguments
问题描述
我正在尝试从 python 运行 tcl 脚本,tcl 脚本需要命令行参数才能执行,当我从 python 获取 tcl 文件时,它会显示错误说
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
我进行了很多搜索,其中大多数询问如何在 tcl 中将参数传递给 python.
I've done many searches, majority of them asks how to pass arguments to python in tcl.
蟒蛇代码
import tkinter
import sys
tclsh.eval('source "test.tcl"' )
if __name__ == '__main__':
print("hi")
tcl 代码
puts [lindex $::argv 0]
无论如何我可以将 python 参数传递给 tcl 吗?
Is there anyway for me pass python arguments to tcl ?
或
不传递参数仍然编译?
因为如果我只编译没有参数的 tcl 脚本,它仍然可以编译
since if I compile tcl script only without arguments, it still compiles
注意:
在 tkinter 文档中它说 tkinter.Tk 是
In tkinter documentation it says tkinter.Tk is
The Tk class is instantiated without arguments
有没有办法用参数实例化?
Is there a way to instantiated with arguments ?
溶胶:
tclsh.eval('set argv [list]')
tclsh.eval('set argc 0')
我试图设置一个全局变量,它在 python 3.6 下对我有用
I tried to set a global variable and it works for me under python 3.6
推荐答案
全局 argv
变量除了在标准 Tcl 脚本启动期间设置外,没有任何特殊之处.因此,您可以在执行 source
之前设置它.在这种情况下,在循环中使用 lappend
这样做可能是最好的,因为它正确构建了变量的结构.还有两个其他变量也应该设置(argc
和 argv0
);总的来说,你这样做(作为一个方便的功能):
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')
{{{}}}
和 Python 的 str.format
导致在参数周围放置一个 单 层大括号,保护反对大多数引用问题.
The {{{}}}
with Python's str.format
results in a single layer of braces being put around the argument, defending against most quoting issues.
这篇关于使用参数从python运行tcl脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!