如何在python中执行线程?

如何在python中执行线程?,python,multithreading,Python,Multithreading,我正在尝试学习如何在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=my

我正在尝试学习如何在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线程是不稳定还是我做错了什么?这个例子来自:

听起来像是IDLE中的一个bug,而不是Python的问题。错误来自Tkinter,这是一个Python GUI工具包,IDLE可能使用它。我会向任何保持空闲的人报告。

不是所有东西都能在空闲状态下正常运行。这是因为IDLE本身就是一个Python程序,它有自己的属性和状态,有时会被自己的代码弄乱。可以看出这是IDLE的问题,因为可以在调用堆栈中看到idlelib。另外,您的应用程序中根本没有使用TCL/TK,但是空闲,调用堆栈也显示了这一点


我建议切换到更“惰性”的文本编辑器来处理Python代码

和往常一样,它只是闲置着。我倾向于建议人们使用与IDLE不同的编辑器。真的只是IPython+你最喜欢的编辑器——vi(我的)、记事本++、Eclipse、Visual Studio。。。随便你喜欢什么。再加上IPython,你真的有点力量。