在 python3 中调用 tcl proc

calling a tcl proc in python3

我正在尝试在 python 程序中调用 tcl proc

tcl 脚本以

开头
proc scale_wigner-seitz_radii { } {

(我不确定我是否可以把完整的过程放在这里,因为这是许可程序的一部分)。

此程序由我的 python 脚本调用:

#!/usr/bin/python3
import sys
from numpy import arange
from tempfile import mkstemp
from shutil import move, copy
from os import remove, close, mkdir, path
import Tkinter


def repll(file_path, pattern, subst):
    print(pattern)
    print(subst)
    print(file_path)
    r = Tkinter.Tk
    # fullpath = str(subst) + "/" + file_path
    fh, abs_path = mkstemp()
    with open(abs_path, "w") as new_file:
        with open(file_path, "r") as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern.strip(),
                                            str(subst).strip()))
    r.tk.eval('source /home/rudra/WORK/xband/create_system_util.tcl')
    r.tk.eval('proc scale_wigner-seitz_radii')
    copy(abs_path, path.join(str(subst), file_path))


inpf = str(sys.argv[1])
a = []
print (inpf)
with open(inpf, "r") as ifile:
    for line in ifile:
        if line.startswith("lattice parameter A"):
            a = next(ifile, "")
            print(a)

for i in arange(float(a)-.10, float(a)+.10, 0.02):
    if not path.exists(str(i)):
        mkdir(str(i))
    repll(inpf, a, i)

我没有举一个最小的例子,因为这似乎比用英语解释更好。

def repll 的最后,它正在调用 tcl proc。之前没遇到过tcl脚本,从this question找到调用过程。 但是当我 运行 这个时,我收到错误:

Traceback (most recent call last):
  File "xband.py", line 41, in <module>
    repll(inpf, a, i)
  File "xband.py", line 24, in repll
    r.tk.eval('source /home/rudra/WORK/xband/create_system_util.tcl')
AttributeError: class Tk has no attribute 'tk'

我该如何解决这个问题?

Donal 发表评论后感谢您的回复。按照你的建议后,我从 source 行得到了同样的错误。

Traceback (most recent call last):
  File "xband.py", line 41, in <module>
    repll(inpf, a, i)
  File "xband.py", line 24, in repll
    r.tk.eval('/home/rudra/WORK/xband/create_system_util.tcl')
AttributeError: class Tk has no attribute 'tk'

对不起,如果它很愚蠢,但由于 tcl 在不同的文件中,我必须先获取它,对吗?而且,正如我所说,这是我正在查看的第一个 tcl 代码,请详细说明。

问题似乎出在这一行:

r = Tkinter.Tk

我的猜测是,您认为这是在创建 Tk 的实例,但您只是在保存对 class 的引用,而不是创建 class 的 实例 。当你实例化它时,返回的对象有一个名为 tk 的属性,对象在内部使用它来引用 tcl 解释器。由于您没有实例化它,r(指向 Tk)没有这样的属性。

要修复它,请通过添加括号来实例化 class:

r = Tkinter.Tk()

r 现在将是对 Tk 对象的正确引用,并且应该具有 tk 属性,这样您就可以在原始 tcl 上调用 eval代码。