首页 > 解决方案 > 如何运行 PowerShell 脚本并将输出发送到 tkinter 文本窗口?

问题描述

有一个工作脚本,可以让我选择一个 PS 脚本并将输出通过管道传输到一个文件。我正在尝试使用 stdout=PIPE 并将其输出到空白的 tkinter 文本框。我和他们一样熟悉编程,我已经做了很多尝试来让它工作但没有成功。有人能指出我正确的方向吗?我没有在这里进行任何尝试,因为我觉得它们完全关闭并且不想弄脏水。 。

from tkinter import *
import tkinter.messagebox as box
import os, subprocess

window = Tk()
window.title( 'PowerShell Script' )

frame = Frame(window)

fldrPath = "\\\\myComputer\share\Power Shell\ps"

listbox = Listbox(frame)

for name in os.listdir(fldrPath):
    listbox.insert('end', name)

def selection():
    fileList = listbox.curselection()
    for file in fileList:
        subprocess.Popen(["powershell.exe", '-ExecutionPolicy', 
                              'Unrestricted', '-File', fldrPath + '\\' +
                              listbox.get(file)], stdout=file_object)

# Use this in selection function as a stdout
file_object = open('c:\\result.txt', 'w')

output = Text(window, width=75, height=6, wrap=WORD, background="white")

btn = Button(frame, text='Run Script', command=selection)

btn.pack(side=RIGHT, padx=5)
listbox.pack(side=LEFT)
frame.pack(padx=30, pady=30)
output.pack(fill=BOTH, expand=1, padx=5, pady=5)

window.mainloop()

标签: pythonpowershelltkinterstdoutpopen

解决方案


推荐阅读