2017-02-20 24 views
0
if __name__=='__main__': 

print("================================================= \n") 

print 'The test will be running for: 18 hours ...' 
get_current_time = datetime.now() 

test_ended_time = get_current_time + timedelta(hours=18) 

print 'Current time is:', get_current_time.time(), 'Your test will be ended at:', test_ended_time.time() 

autodb = autodb_connect() 
db = bw_dj_connect() 

started_date, full_path, ips = main() 



pid = os.getpid() 

print('Main Process is started and PID is: ' + str(pid)) 

start_time = time.time() 

process_list = [] 

for ip in ips: 
    p = Process(target=worker, args=(ip, started_date, full_path)) 
    p.start() 
    p.join() 
    child_pid = str(p.pid) 
    print('PID is:' + child_pid) 
    process_list.append(child_pid) 

child = multiprocessing.active_children() 
print process_list 

while child != []: 
    time.sleep(1) 
    child = multiprocessing.active_children() 


print ' All processes are completed successfully ...' 
print '_____________________________________' 
print(' All processes took {} second!'.format(time.time()-start_time)) 

我有一個python測試腳本,應該運行18個小時然後自殺。該腳本對多設備使用多處理。我從main()函數獲得的數據將隨時間而改變。如何在Python中運行18小時的腳本?

我將這三個參數傳遞給多處理中的工作方法。

我該如何做到這一點?

+0

你問過如何殺死一個過程,或者如何判斷18小時過去了嗎? –

+0

您可能會發現使用終端命令「timeout」運行腳本會更容易。 – BallpointBen

+0

「我怎樣才能做到這一點」之前的描述使得聽起來就像你已經「達到了」那樣。 –

回答

0

如果你不需要擔心清理對孩子過多進程,你可以使用.terminate()

... 
time.sleep(18 * 60 * 60) # go to sleep for 18 hours 
children = multiprocessing.active_children() 
for child in children: 
    child.terminate() 

for child in multiprocessing.active_children(): 
    child.join() # wait for the children to terminate 

殺死他們,如果你確實需要做一些清理工作中的所有子進程,那麼你需要修改他們的運行循環(我假設爲while True)來監視時間傳遞,並且只有主程序中的第二個while循環,等待孩子獨自離開。

0

你永遠不會比較datetime.now()和test_ended_time。

# check if my current time is greater than the 18 hour check point. 
While datetime.now() < test_ended_time and multiprocessing.active_children(): 
    print('still running my process.') 

sys.exit(0) 
相關問題