从 TCL 调用 Python 代码并检查其 return 值

Calling Python code from TCL and checking its return value

我需要在 TCL 脚本中调用 Python 代码并检查其退出状态以确定 Python 代码是否执行成功。

TCL脚本:

if {[catch {exec "python C:\tools\tcl\myexamples\sample.py"} results] == 0 } {
    puts "No Error $results"
} else {
    puts "Error $results"
}

Python代码:

import sys

def main():
    return 0

if __name__ == '__main__':
    return main()

但是,当我执行 TCL 脚本时,出现以下错误:

$ tclsh85.exe  ../myexamples/1.tcl
Error couldn't execute "python C:\tools\tcl\myexamples\sample.py": no such file or directory

但文件确实存在:

C:\tools\tcl\myexamples>dir sample.py
Directory of C:\tools\tcl\myexamples
07-08-2019  11:23 AM               199 sample.py
1 File(s)            199 bytes

这是什么问题,我该如何解决?

对于exec,只有带空格的参数需要引号,而不是整个参数列表。

使用 TKCon 2.7(来自 ActiveState TCL 8.6 的安装)我尝试了以下操作:

exec "python c:\writing\scripts\my_py.py"

找不到 "python c:\writing\scripts\my_py.py"。

exec python c:\writing\scripts\my_py.py

运行脚本正常。 exec "python" "c:\writing\scripts\my_py.py".

也是

正在创建名为 my_py space.py 的 my_py.py 副本,然后运行 ​​

exec python "c:\writing\scripts\my_py space.py"

也运行脚本正常。

所以看起来 exec 只需要为其中有空格的单个参数加上引号。

exec 命令将脚本的每个参数作为单独的 Tcl 参数。这意味着简单的解决方法是更改​​:

exec "python C:\tools\tcl\myexamples\sample.py"

至:

exec python "C:\tools\tcl\myexamples\sample.py"

但我实际上更愿意写:

exec python [file nativename C:/tools/tcl/myexamples/sample.py]

或者,如果它与当前 Tcl 脚本在同一目录中:

exec python [file nativename [file join [file dirname [info script]] sample.py]]

一般来说,其中一些是您要在脚本开头记录的内容:

set ThisDir [file normalize [file dirname [info script]]]

然后你就可以做到这一点:

exec python [file nativename [file join $ThisDir sample.py]]