如何在Python中运行脚本18个小时?

时间:2017-02-20 16:10:43

标签: python python-2.7 time multiprocessing

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()函数获得的数据将随时间变化。

我将这三个args传递给多处理中的worker方法。

我怎样才能做到这一点?

2 个答案:

答案 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循环在主程序,等待孩子自己离开。

答案 1 :(得分:0)

你永远不会将datetime.now()与test_ended_time进行比较。

=RANK(AK7,$AK$7:$AK$10)