无法建立在python
我有下面的代码一个线程用于比较用户输入无法建立在python
import thread,sys
if(username.get_text() == 'xyz' and password.get_text()== '123'):
thread.start_new_thread(run,())
def run():
print "running client"
start = datetime.now().second
while True:
try:
host ='localhost'
port = 5010
time = abs(datetime.now().second-start)
time = str(time)
print time
client = socket.socket()
client.connect((host,port))
client.send(time)
except socket.error:
pass
如果我只是调用函数的run()它的工作原理,但是当我尝试创建一个线程来运行该功能,因故未创建线程,而不是执行run()函数,我无法找到任何错误..提前
谢谢...
你真的应该使用threading
模块,而不是thread
。
你还在做什么?如果你创建这样一个线程,那么如果线程仍在运行解释器将退出不管与否
例如:
import thread
import time
def run():
time.sleep(2)
print('ok')
thread.start_new_thread(run,())
- >这将产生:
Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
其中:
import threading
import time
def run():
time.sleep(2)
print('ok')
t=threading.Thread(target=run)
t.daemon = True # set thread to daemon ('ok' won't be printed in this case)
t.start()
按预期工作。如果你不想让解释器等待这个线程,只需在生成的Thread上设置daemon = True *即可。
*编辑:补充说,例如,在
我知道thread.start_new_thread是一个有限的库,我最初使用threading.thread,创建线程并运行函数也被调用,但问题是代码在while循环中被触发。有线程的全部目的被击败,所以我尝试使用thread.start_new_thread。简而言之,我的问题仍未解决。当我在我的代码中创建一个线程时,代码在while循环中被触发。也请尽量解决我的代码,我知道你给出的run()定义很简单,它的工作原理。 – nitinsh99 2012-04-29 16:28:16
当然是卡在一个循环中。如果你不想这样做,你必须有办法以某种方式结束该线程。 [this](http://pastebin.com/YcRnyEbK)通过将线程设置为守护进程线程来工作,这意味着当没有其他(非deamon)线程正在运行时它将被终止。 – mata 2012-04-29 17:19:46
可以请你解释一下wid一些代码,我听说过守护线程,但不知道如何使用它.. thnx for replyin – nitinsh99 2012-04-30 18:22:22
thread
是一个低级别的库,你应该使用threading。
from threading import Thread
t = Thread(target=run, args=())
t.start()
你能提供一个最小运行的例子吗?此代码不会运行,因为名称'username'和'password'未定义。 – 2012-04-28 14:26:36