2013-05-17 47 views
2

我想写一个程序为我的网络课程,我有一个套接字,如果它侦听并接收数据,我应该终止程序,我使用threading.Timer像计时器,并有像我的功能监听t = threading.Timer(5, end_data)线接收数据,但我不能在end_data即终止程序:停止python程序

def end_data(): 
    sys.exit() 

任何一个能帮助我吗? 我还测试下面的代码芽终端:(

def end_data(): 
    try: 
     sys.exit() 
    except: 
     print"exception" 

我期待并没有终止正在运行的程序,当停止终端打印蒂娜丝-的MacBook-Pro的:〜蒂娜$

,我听插座命名函数接收不主,当经过5第二,没有数据接收,它将运行end_data和似乎永远不会返回到接收功能,这种功能的一部分是像下面

def receive(): 
    s2 = socket(AF_INET, SOCK_DGRAM) 
    s2.bind(addr3_2) 
    global end_call 
    global base_window 
    write=open('pictur.jpg','wb') 
    s = socket(AF_INET, SOCK_DGRAM) 
    s.bind(addr3) 
    while(end_call==0): 
     t = threading.Timer(5, end_data) 
     t.start()  
     recv_data, addr = s.recvfrom(3500)#size ro hala badan check kon 
     t.cancel() 

第一我决定5后设置的全局变量end_call其次,但它没有工作,因为它从来没有回来接收功能

一些事情,这是非常有趣的,我是,如果定义DATA_END像:

def end_data(): 
    os._exit 
    print "Hi" 

喜将在输出打印:o

+0

一些有用的信息,请参阅本:http://stackoverflow.com/questions/905189/why-does-sys-exit-not-exit-when-called-inside-a-thread-in-python 。你可以尝试使用'os._exit',但这通常被认为有点不礼貌(它不允许清理任何东西) – mgilson

+0

你在最后一个例子中打印“Hi”的原因是,实际上不*调用*'os._exit' - 尝试用'os._exit()'替换'os._exit'。 –

+0

我尝试它但得到错误:TypeError:_exit()只需要1个参数(0给出) – sandra

回答

0

也许尝试这样

run_program = True 

def end_data() : 
    global run_program 
    run_program = False 

t = threading.Timer(5, end_data) 
t.start() 

while run_program: 
    #do stuff 
    time.sleep(1) 

t.join() #maybe not needed 

的设置确保你叫t.start():)

+0

我认为你需要在'end_data'中创建'run_program'“'global'”。 – mgilson

+0

啊,你是对的。 – beiller

+0

我正在监听socket函数,名为receive not main,当经过5秒钟没有数据接收时,它会运行end_data,并且似乎永远不会返回到接收函数 – sandra

0

要回答你的第二个问题,请使用try,except

这是每pydoc预期的行为:

"Since exit() ultimately “only” raises an exception, it will only exit 
the process when called from the main thread, and the exception is not intercepted." 

例子:

def end_data(): 
    try: 
     sys.exit("error!") 
    except SystemExit, e: 
     print "Exception caught: ", e.args 


print "begin" 
end_data() 
print "end" 

输出:

$ ./test.py 
begin 
Exception caught: ('error!',) 
end 
0

有关使用线程活动是什么?

import threading 

event = threading.Event() 

def signal_stop(): 
    try: 
     # do what you have to do 
    finally: 
     event.set() 


t = threading.Timer(5, signal_stop) 

print 'start thread and wait for it' 
t.start() 
event.wait() 
print 'done'