从Python脚本传递变量到tcl shell

3

我是新来的,如果有任何错误,请提前谅解。我正在尝试从我的Python代码传递一个变量到TCL脚本。我现在的做法是:

import os
import Tkinter
from Tkinter import *

def set_impairments(port,delay):

    port=int(port)
    delay=int(delay)
    tcl = Tcl()
    tcl.eval("""
    proc my_proc {in_port,in_delay} {

    puts in_port
    puts in_delay
    }
    """)
    print port
    print delay

    tcl.eval('my_proc port,delay')

set_impairments(0,25000)

这段代码的输出结果是:
0

25000

in_port

in_delay

如何将in_port分配为0,in_delay分配为25000?我无法理解为什么无法传递变量的值。

这部分内容与 https://stackoverflow.com/questions/25288972/pass-python-variables-to-tkinter-tcl-eval 有些重复,但您也可以使用下面的 'eval' + format 解决方案,而不是使用 Tkinter StringVar。 - schlenk
是的,我已经阅读了那个线程,但它并没有帮助到我。显然,我没有理解Glenn建议使用$来引用变量值的要点。无论如何,谢谢。 - wolf123
1个回答

3

Tcl不使用逗号来分隔参数,而是使用空格。此外,您需要使用 $ 来引用变量的值。请按照以下方式操作:

proc my_proc {in_port in_delay} {
    puts $in_port
    puts $in_delay
}

我并不是一个专业的Python开发者,但你可能需要

tcl.eval('my_proc {0} {1}'.format(port,delay))

1
可以将调用写得更好看一些,如tcl.call('my_proc', port, delay),其中有一点魔法,因此您不需要移动字符串表示。但并非所有的 Python 变量类型都适用,但 int / string 可以。 - schlenk
非常感谢你,Glenn。这很有帮助。 - wolf123
谢谢Schlenk。我一定会看一下的。 - wolf123

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接