我正在尝试学习如何在python中使用线程。这是我一直在研究的代码:
import time
from threading import Thread
def myfunc(i):
print "sleeping 5 sec from thread %d" % i
time.sleep(5)
print "finished sleeping from thread %d" % i
for i in range(10):
t = Thread(target=myfunc, args=(i,))
t.start()
程序在命令提示符下正常运行,但是当我尝试在空闲状态下运行时,我得到这样的错误:
Traceback (most recent call last):
File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__
return self.func(*args)
File "C:\Python24\lib\idlelib\ScriptBinding.py", line 165, in run_module_event
interp.runcode(code)
File "C:\Python24\lib\idlelib\PyShell.py", line 726, in runcode
self.tkconsole.endexecuting()
File "C:\Python24\lib\idlelib\PyShell.py", line 901, in endexecuting
self.showprompt()
File "C:\Python24\lib\idlelib\PyShell.py", line 1163, in showprompt
self.resetoutput()
File "C:\Python24\lib\idlelib\PyShell.py", line 1178, in resetoutput
self.text.insert("end-1c", "\n")
File "C:\Python24\lib\idlelib\Percolator.py", line 25, in insert
self.top.insert(index, chars, tags)
File "C:\Python24\lib\idlelib\PyShell.py", line 315, in insert
UndoDelegator.insert(self, index, chars, tags)
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 81, in insert
self.addcmd(InsertCommand(index, chars, tags))
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 116, in addcmd
cmd.do(self.delegate)
File "C:\Python24\lib\idlelib\UndoDelegator.py", line 216, in do
if text.compare(self.index1, ">", "end-1c"):
File "C:\Python24\lib\lib-tk\Tkinter.py", line 2784, in compare
return self.tk.getboolean(self.tk.call(
TclError: expected boolean value but got ""
python线程是不稳定还是我做了一件非常错误的事情?该示例来自:http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/
答案 0 :(得分:1)
这听起来像是IDLE中的一个错误,而不是Python的问题。错误来自Tkinter,它是一个Python GUI工具包,IDLE可能会使用它。我会向任何维持IDLE的人报告。
答案 1 :(得分:1)
并非一切都在IDLE下正常运行。这是因为IDLE本身就是一个Python程序,它有自己的属性和状态,有时会被你自己的代码弄乱。您可以告诉这是IDLE的一个问题,因为您可以在调用堆栈中看到idlelib。此外,您在应用程序中根本不使用TCL / TK,但IDLE是,并且调用堆栈也显示了这一点。
我建议切换到一个更“惰性”的文本编辑器来处理Python代码!