2013-05-17 48 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'