【发布时间】:2017-08-07 21:47:41
【问题描述】:
在线程中,我有一个从用户控制台读取输入的循环。主线程正忙于 Tkinter mainloop()。如何终止此程序?
while True: ln = sys.stdin.readline() try: ln = ln[:-1] # Remove LF from line if len(ln)==0: continue # Ignore blank lines ...and so on主线程调用 startGUI(),其中包含一个 tk.mainloop() 调用。当我按下窗口(这是 Linux)上的 X 关闭按钮时,Tkinter 关闭窗口并且 mainloop() 返回。然后我尝试关闭 stdin,希望 sys.stdin 将关闭并导致 sys.stdin.readline() 将以一个不错的 EOF 终止,从而允许我的 stdinLoop 线程终止。
# Start up the GUI window startGUI() # Doesn't return until GUI window is closed, tk.mainloop is called here # # Wait for stdinLoop thread to finish sys.stdin.close() # Hopefully cause stdinTh to close print("waiting for stdinTh to join") stdinTh.join() print("joined stdinTh")
sys.stdin.realine() 在 sys.stdin.close() 之后永远不会返回。 (stdinTh.join() 用于同步关闭。)
我认为 Python readline() 正在做一些 聪明的(在称为 NetCommand 的东西中),当 stdin 关闭时不会干净地返回。
Python 是否认为同时拥有 Tkinter GUI 和交互使用标准输入是邪恶?
我尝试使用 sys.stdin.read(1),但似乎缓冲了一行并返回整行——而不是像我认为 read(1) 那样读取一个字节/字符。
【问题讨论】:
-
Python 并不认为它是邪恶的,但它肯定不是 GUI 程序的设计运行方式。根据您启动 GUI 的方式,甚至可能没有可供读取的标准输入。您想通过 GUI 和从标准输入读取来完成什么?
-
@BryanOakley,是的,不是传统的,我使用控制台向应用程序输入“调试”命令。 GUI 是(最终)用户将与之交互的真实事物。
标签: python multithreading python-2.7 tkinter