【问题标题】:Running tcl script from python with arguments使用参数从 python 运行 tcl 脚本
【发布时间】:2019-09-12 15:45:26
【问题描述】:

我正在尝试从 python 运行 tcl 脚本, tcl 脚本需要命令行参数才能执行,当我从 python 获取 tcl 文件时,它会显示错误提示

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

我进行了很多搜索,其中大多数询问如何在 tcl 中将参数传递给 python。

python 代码

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

tcl 代码

puts [lindex $::argv 0]

无论如何我可以将 python 参数传递给 tcl 吗?

不传递参数并且仍然编译?

因为如果我只编译不带参数的 tcl 脚本,它仍然可以编译

注意:

在 tkinter 文档中它说 tkinter.Tk 是

The Tk class is instantiated without arguments

有没有办法用参数实例化?

索尔:

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

我尝试设置一个全局变量,它适用于我在 python 3.6 下

【问题讨论】:

  • 检查this question的回答是否有帮助?
  • @Jerry 嗨,我猜不,这个问题是将函数参数传递给 tcl 函数,我正在尝试将参数传递给 tcl 命令行参数...

标签: python tkinter tcl


【解决方案1】:

全局argv 变量除了在标准Tcl 脚本的启动期间设置外,在任何方面都没有特殊性。因此,您可以在执行source 之前设置它。在这种情况下,在循环中使用lappend 这样做可能是最好的,因为它可以正确构建变量的结构。还有两个其他变量也应该设置(argcargv0);总的来说,你这样做(作为一个方便的功能):

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 导致在参数周围放置一个层大括号,以防止大多数引用问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多