Python的线程(Thread)(最后更新2008.01.11)
目的:打开一个HTTP Server (这个不能关闭,因为还要接受一些信息),然后再打开一个网络浏览器(IE或Firefox)。
我试了试:
import time
import thread
def myFunction(number, interval):
while True:
print 'Thread :(%d) Time:%s'%(number,time.ctime())
time.sleep(interval)
def mainFunction():
thread.start_new_thread(myFunction,(1,1))
thread.start_new_thread(myFunction,(2,3))
if __name__=='__main__':
mainFunction()
运行这个程序,什么反应都没有!
但是,把这句:time.sleep(5)加在mainFunction()下面,就有反应了。
下面复杂一点:
import time
import thread
def myFunction1():
while True:
import SimpleHTTPServer
SimpleHTTPServer.test()
time.sleep(1)
def myFunction2():
while True:
import webbrowser
webbrowser.open('http://127.0.0.1:8000/')
time.sleep(1)
def mainFunction():
thread.start_new_thread(myFunction1,())
thread.start_new_thread(myFunction2,())
if __name__=='__main__':
mainFunction()
time.sleep(1)
看到了~在IE中看到了~但是命令提示符下面的HTTP Server也关闭了。
这里我想了想,搜了搜,好像应该一个是父进程,一个是子进程。
修改之:
import thread
def childThread():
import webbrowser
webbrowser.open('http://127.0.0.1:8000/')
def parentThread():
while True:
import SimpleHTTPServer
SimpleHTTPServer.test()
thread.start_new_thread(childThread,())
if __name__=='__main__':
parentThread()
结果IE窗口蹦不出来了。
我想是HTTP Server“暂停”了主进程的缘故,而退出HTTP Server又只能Ctrl+Break,直接退出主进程了。
我想应该主进程什么都不放,先出来一个子进程HTTP Server,再出来一个子进程IE窗口。
再试试:(未完) (我不喜欢呀~)
页:
[1]