Python: terminate a multithreading program after some time using daemon thread -


i want implement program terminate after running time t, , t read command line using argumentparser. have following code (omit details):

def run():     parser = create_arg_parser()     args = parser.parse_args()     class_instance = multithreadclass(args.arg1, args.arg2)     class_instance.run()  if __name__ == '__main__':     run_thread = thread(target=run)     run_thread.daemon = true     run_thread.start()     time.sleep(3.0) 

the program works expect (it terminates after running 3 seconds). mentioned before, running time (3.0 in code snippet above) should input command line (eg. args.arg3 = 3.0) instead of hard coded. apparently cannot put time.sleep(args.arg3) directly. wondering if there approach solve problem? answers without using daemon thread welcome! thanks.

ps. if put argument parsing code outside of run function like:

def run(args):     class_instance = multithreadclass(args.arg1, args.arg2)     class_instance.run()  if __name__ == '__main__':     parser = create_arg_parser()     args = parser.parse_args()     run_thread = thread(target=run(args))     run_thread.daemon = true     run_thread.start()     time.sleep(args.arg3) 

the program not terminate after args.arg3 seconds , i'm confused reason. appreciative if 1 explain magic behind of these... lot!

in second example, when creating thread should pass function, , args should come second argument. this:

thread(target=run, args = (args.arg1, args.arg2)) 

so in 2nd example evaluate function before creating thread , returning none run function thread class.

also, according docs, when specifying daemon = true:

the significance of flag entire python program exits when daemon threads left

this should work:

def run(arg1,arg2):     class_instance = multithreadclass(arg1, arg2)     class_instance.run()  if __name__ == '__main__':     parser = create_arg_parser()     args = parser.parse_args()     run_thread = thread(target=run, args=(args.arg1, args.arg2))     run_thread.start()     time.sleep(args.arg3) 

this post start threads, furthermore read docs better understand "magic".


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -