pause/resume a python script in middle

后端 未结 9 1480
再見小時候
再見小時候 2020-12-28 16:38

Can I have a running python script(under Windows)being paused in the middle by user , and resume again when user decides ?

There is a main manager program which gen

9条回答
  •  無奈伤痛
    2020-12-28 17:14

    If it were unix I'd recommend signal, but here is a crude version that does what you ask.

    import time
    
    while True:
        try:
            time.sleep(1)  # do something here
            print '.',
    
        except KeyboardInterrupt:
            print '\nPausing...  (Hit ENTER to continue, type quit to exit.)'
            try:
                response = raw_input()
                if response == 'quit':
                    break
                print 'Resuming...'
            except KeyboardInterrupt:
                print 'Resuming...'
                continue
    

    Use Ctrl+C to pause, and ENTER to resume. Ctrl+Break can probably be used as a harsh kill, but I don't have the key on this keyboard.

    A more robust version could use select on a pipe/socket, or even threads.

提交回复
热议问题