回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我一直在尝试从运行了一段时间的Powershell脚本中读取stdout,并根据正在ping的计算机数量生成输出</p>
<p>尝试将数据流式传输到文本框中,但经过所有尝试,我似乎只能让它一次给出所有输出</p>
<p>我一直试图不使用<code>subprocess.communicate()</code>,因为它似乎同时提供所有输出</p>
<p>代码如下:</p>
<pre><code>from tkinter import *
import os
from subprocess import Popen, PIPE
window = Tk()
window.title( 'PowerShell Script Temp' )
frame = Frame(window)
fldrPath = r"C:/Users/firstname.lastname/Downloads/Powershell Development/Monthly Scans/"
listbox = Listbox(frame)
listbox.configure(width=50)
for name in os.listdir(fldrPath):
listbox.insert('end', name)
def selection():
fileList = listbox.curselection()
for file in fileList:
os.chdir(fldrPath)
# Right here is the problematic section
with Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)], stdout=PIPE, bufsize=1,
universal_newlines=True) as p:
for line in p.stdout:
output.insert('end', line)
print(line, end='')
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()
</code></pre>
<p><a href="https://i.stack.imgur.com/BcGDx.png" rel="nofollow noreferrer">Doesn't filter line-by-line</a>-在PS脚本完成后,只需将其全部吐出即可</p>
<p>我尝试了很多其他的方法:</p>
<h2>尝试1</h2>
<pre><code>proc = subprocess.Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)], shell=True, stdout=PIPE)
while proc.poll() is None:
data = proc.stdout.readline() # Alternatively proc.stdout.read(1024)
print(data)
text_box.insert('end', data)
</code></pre>
<h2>尝试2</h2>
<pre><code>outpipe = subprocess.Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE).communicate()[0]
text_box.insert("end", outpipe)
</code></pre>
<h2>尝试3</h2>
<pre><code>with Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)], stdout=PIPE, bufsize=1,
universal_newlines=True) as p, StringIO() as buf:
for line in p.stdout:
print(line, end='')
buf.write(line)
outpipe = buf.getvalue()
output.insert('end', outpipe)
</code></pre>
<h2>尝试4</h2>
<pre><code>proc = subprocess.Popen(["powershell.exe", '-File', fldrPath + '\\' + listbox.get(file)], shell=True,
stdout=subprocess.PIPE)
while proc.poll() is None:
p = proc.stdout.readline()
output.insert('end', p)
</code></pre>
<p>事实上,我尝试了更多,但似乎记不起来了。有很多优点和缺点…现在我有点厌倦了😔. 我可以用我想要的方式把这个东西<code>Print()</code>,但不能流到文本框中;几乎就像<code>.insert()</code>太慢了</p>
<p>如果有人能把我引向正确的方向,我将不胜感激。我在这里尝试了几乎所有我能处理的类似线程,但似乎没有达到目的</p>