通过子进程通过python运行TCL,但不提供任何输出

时间:2013-01-10 17:49:28

标签: python tkinter tcl eval subprocess

我试图通过python子进程运行我的tcl脚本,如下所示:

import subprocess
>>> subprocess.Popen(["tclsh", "tcltest.tcl"])
<subprocess.Popen object at 0x0000000001DD4DD8>
>>> subprocess.Popen(["tclsh", "tcltest.tcl"], shell=True )
<subprocess.Popen object at 0x0000000002B34550>

我不知道它是否有效,因为我没有看到任何东西! 我的tcl脚本也有我公司的一些软件包,当我使用Tkinter,Tk和eval时会导致错误,

import Tkinter
import socket

def TCLRun():
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect(('127.0.0.1', 5006))
 root = Tkinter.Tk()
## root.tk.eval('package require Azimuth-Sdk')
 tcl_script ="""
##package require Company-Sdk
## set players [ace_azplayer_list_players]
set players 2
puts $players 
##  if { $players != "" } {         
##  foreach player $players {   
##      set cmd ace_azplayer_remove_player
##      if { [catch { [ $cmd $player ] } err] } {   
##          puts " $cmd $player - $err" 
##          sleep 1 
##          }           
##      } 
##  } """
 # call the Tkinter tcl interpreter
 root.tk.call('eval', tcl_script)
 root.mainloop()

给我这个错误

import TCLCall
>>> TCLCall.TCLRun()

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    TCLCall.TCLRun()
  File "C:\Users\XXX\Desktop\PKT\TCLCall.py", line 24, in TCLRun
    root.tk.call('eval', tcl_script)
TclError: can not find channel named "stdout"

这就是我切换到子进程的原因。至少它不会给我错误!

任何想法如何通过python运行我的tcl脚本与内部必需的包?!

由于

3 个答案:

答案 0 :(得分:2)

要使用subprocess.Popen获取输出,您可以尝试以下操作:

import subprocess

p = subprocess.Popen(
    "tclsh tcltest.tcl",
    shell=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print stdout
print stderr

您使用subprocess.Popen运行的脚本完全有可能也会生成错误,但由于您没有明确查找错误,因此无法显示。

修改

为防止某些信息在以下评论中丢失:

这里可能有几个潜在的错误,或者你可以尝试的东西。

您的tcl脚本本身无法正确导入teapot,或者tcl脚本与python脚本之间的某种交互无法正常工作,或者subprocess.Popen不正常正确地从您的路径中找到teapot包。

我会尝试按顺序调试你的程序。首先确认您的tcl脚本在不使用python或subprocess.Popen的情况下工作,并直接从命令行运行它(例如,C:\Users\blah tclsh tcltest.tcl

然后,在确定脚本工作之后,引入Python。从我所看到的,你对python的东西没有任何问题,但你的tcl脚本或你的路径有一些问题。

答案 1 :(得分:1)

subprocess.Popen的重点是标准通道的重定向,因此您可以以编程方式处理输出,而不是在您自己的标准输出上查看。你试过处理吗?怎么样?

也许你根本不需要重定向:那么os.system("tclsh tcltest.tcl")就足够了。或者subprocess.Popen可能还有其他优点 - 然后弄清楚如何禁用重定向,或者如何将子标准重定向到您自己的标准输出。

答案 2 :(得分:0)

我想我可能会为您提供解决方案。或至少尝试其他方法。本示例将TCL Shell作为进程打开。然后,您就像在命令行上一样向其泵送命令。既然您说您的命令行有效,那么我认为也可以。在Windows上使用Python 3.7.6和TCL 8.5时,这对我有效。

需要一些技巧。我发现解决方案需要线程和各种其他开销才能完成这项工作,但它们只是失败了。我想到的是简单而同步的。

stdout.readline()将被阻止。因此,如果您的TCL命令什么也没扔掉,那么您就死定了。

因此,您通过附加一个无害的TCL puts命令来强制返回某些内容,该命令将与完成工作的Python脚本进行通信。

另一个技巧是您需要“放入[]”命令以将输出强制返回到stdout。

如果您需要获取更多的TCL文件,请在对要运行的文件进行最终调用之前添加这些文件。无论您需要在cli上做什么,都需要完成此过程。

我的代码将所有内容包装在带有方法的类中。我将它们全部串联在一起作为示例。在调试时将errorInfo代码保留在其中,并根据需要删除。

注意:您还可以使用TCL“信息主体”将脚本读入字符串变量,然后在该过程中运行每一行。从本质上讲,如果在Python调试会话中逐步执行TCL。对不起,这样做效果不佳。注释的解决方法不适用于打开花括号。

希望这可以帮助某个人。

编辑:使用多行字符串处理注释行。

import subprocess

print("------")
shell_path = r"<YOUR PATH TO THE TCL INTERPRETER SHELL>"
tcl_shell = subprocess.Popen(shell_path,
                    stdin =subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    universal_newlines = True,
                    bufsize = 0)

#
# Use ONE of the "command"s below. I have them here in series for exmaples.
#

# Simple
command = r"set temp 5"

# Multiline with error --> This will give an error of course to see the error extraction in action
command = r"""
    set temp 5
    set temp2 [expr temp + 5]
"""

# Multiline working
command = r"""
    set temp 5
    set temp2 [expr $temp + 5]
"""

# More output
command = r"""
    puts "Starting process"
    set temp 5
    puts $temp
    set temp2 [expr $temp + 5]
"""

# Comments handled
command = r"# comment!"

# Be sure to leave the newline to handle comments
tcl_shell.stdin.write(f"""puts [{command}
                                ] \nputs \"tcl_shell_cmd_complete\"\n""")
# NOTE: tcl_shell.stdin.flush() does not seem to be needed. Consider if needed.
result = ""
line = tcl_shell.stdout.readline()
while line != "tcl_shell_cmd_complete\n":
    result += line
    line = tcl_shell.stdout.readline()

print(f"tcl_shell sent:\n{command}")
print(f"tcl_shell result:\n{result}".rstrip())

command_error_check = "puts $errorInfo"
tcl_shell.stdin.write(f"{command_error_check} \nputs \"tcl_shell_cmd_complete\"\n")
resultErr = ""
line = tcl_shell.stdout.readline()
while line != "tcl_shell_cmd_complete\n":
    resultErr += line
    line = tcl_shell.stdout.readline()

print(f"tcl_shell error info:\n{resultErr}")

tcl_shell.stdin.close()
tcl_shell.terminate()
tcl_shell.wait(timeout=0.5)
print("------")