我正在编写一个 python 应用程序来获取用户的一些输入并根据这些输入调用 shell 脚本。
这个 shell 脚本可以运行相当长的一段时间,我想将它生成的输出(实时)重定向到 tkinter。
我设法做到了这一点,但它仅在 shell 脚本完全完成后发生,而不是在 shell 脚本“回显”某些内容后立即发生。
所以主要问题:
1. 仅在退出 shellScript.sh 后,输出才会出现在文本小部件中(尽管如果我在终端中手动运行相同的内容,我会看到连续的输出)。
2.附带问题:输出中打印的所有“\n”都只是打印为“\n”,并且文本小部件中没有添加新行。
这是我所拥有的:
class RedirectText(object):
def __init__(self, text_ctrl):
"""Constructor"""
self.output = text_ctrl
def write(self, string):
self.output.insert(tk.END, string[2:])
class Gui(GuiApp):
def __init__(self, master=None):
redir = RedirectText(self.text_Output)
sys.stdout = redir
def testRun(self, event=None):
p = subprocess.Popen(["./shellScript.sh"], stdout=subprocess.PIPE)
print(p.communicate()[0])
As p.communicate()
将等待该过程完成,因此使用p.poll()
and p.stdout.readline()
反而。同样将进程放在一个线程中以避免阻塞主线程:
import threading
...
class Gui(GuiApp):
...
def runScript(self):
print('started')
p = subprocess.Popen(['./shellScript.sh'], stdout=subprocess.PIPE, bufsize=1, text=True)
while p.poll() is None: # check whether process is still running
msg = p.stdout.readline().strip() # read a line from the process output
if msg:
print(msg)
print('finished')
def testRun(self, event=None):
# create a thread to run the script
threading.Thread(target=self.runScript, daemon=True).start()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)