簡體   English   中英

如何在Python中運行腳本18個小時?

[英]How can I run a script for 18 hours in Python?

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()函數獲取的數據將隨時間更改。

我將這三個參數傳遞給多處理程序中的worker方法。

我該如何實現?

如果您不必擔心過多清理子進程,則可以使用.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循環,等待孩子們自己走開。

您永遠不會將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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM