python - 将 TCL 脚本的输出记录到 Tkinter 文本小部件中

标签 python python-2.7 logging tkinter tcl

我已经做了两件事,现在我想将这两件事合并起来。 我在 Windows 8 上使用命令提示符

  1. 我有一个可以从 python 运行的 TCL 文件。它在命令提示符下给出所有输出。我用这个命令来运行TCL

    os.system(r'vivado -mode tcl -source location/my_tcl.tcl')

完整代码:

import Tkinter as tk
import os
import time

my_gui = tk.Tk()
mvar = tk.StringVar()

def my_hello():
    chk = mvar.get()
    if chk == '1':
        os.system(r'vivado -mode tcl -source path/my_tcl.tcl')
        f = open('input.txt', 'r')
        a = f.readline().rstrip('\n')
        if a == 'Passed':
            mlabel = tk.Label(my_gui,text = 'Test Passed', fg = 'black', bg = 'green',width = 10).place(x=200,y=10)
        else:
            mlabel = tk.Label(my_gui,text = 'Test Failed', fg = 'black', bg = 'red',width = 10).place(x=200,y=10)
        f.close
    else:
        mlabel = tk.Label(my_gui,text = 'No Test Run', fg = 'black', bg = 'yellow',width = 10).place(x=200,y=10)

my_gui.geometry('300x300+200+200')
my_gui.title('Test')

mbutton = tk.Button(my_gui,text = 'Run Tests!',command = my_hello).place(x=150,y=280,anchor= 'center')

check1 = tk.Checkbutton(my_gui,text = 'DDR Test',state = 'active', variable = mvar).place(x=10,y=10)
mvar.set('0')


my_gui.mainloop()
  • 我已经在 python 上实现了简单的日志记录,遵循此线程的解决方案:Python Logging to Tkinter Text Widget
  • 完整代码:https://gist.github.com/bitsgalore/901d0abe4b874b483df3ddc4168754aa

    现在我想将这两部分结合起来,但日志记录需要某种字符串输入才能存储和显示日志。而 TCL 的输出出现在命令提示符上。我想要实现的是命令提示符上显示的所有内容都可以在我的 Tkinter 文本小部件上可见。

    有什么办法可以做到这一点吗? 问候

    最佳答案

    这是一种有点静态的方法。 您可以使用 subprocess 模块,它允许您捕获进程的输出,然后将其显示在 tkinter.Text 小部件中。

    import subprocess
    
    def run_process():
        path = "script_with_some_output"
        p = subprocess.run(path, stdout=subprocess.PIPE)
    
        return p.stdout
    

    现在,您可以调用 run_process() 来执行您的进程,并以字节序列的形式获取其输出。 您可以通过调用 text.insert(tk.END, run_process()) 轻松地将其记录到 Text 小部件中。

    这是一个简短的示例来演示这一点:

    import tkinter as tk
    import sys
    import subprocess
    
    def run_process():
        path = r"path/to/script"
        p = subprocess.run("python"+path, stdout=subprocess.PIPE)
        return p.stdout
    
    root = tk.Tk()
    log = tk.Text(root)
    b = tk.Button(root, text="Run stuff", command=lambda: log.insert(tk.END, run_process()))
    
    log.pack()
    b.pack()    
    
    root.mainloop()
    

    此脚本将运行位于给定路径的脚本,并在文本小部件中显示其输出。

    关于python - 将 TCL 脚本的输出记录到 Tkinter 文本小部件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075544/

    相关文章:

    python - 将 python 标志 cx_freeze 添加到可执行文件

    python-2.7 - TEXTBLOB 计算的极性分数背后的逻辑?

    python - 我们如何杀死 python 中 subprocess.call() 函数产生的进程?

    logging - 安排特定文件存储在 AWS 的 EBS 卷上

    linux - 如何将控制台打印记录到带有时间戳的文件中

    python - ValueError : too many values to unpack (expected 1)?

    python - "overloading"不适用于 stderr

    Python 模块 httplib2 和 python 路径

    python - 获取字符之前和之后的字符串,然后将它们设置为变量 Python

    logging - Heroku Redis 日志很嘈杂——如何过滤掉它们?