On Mon, Jun 2, 2014 at 3:14 PM, Rahul Gopan <rahulpce...@gmail.com> wrote:

> Hello,
>
> When I run a python script it hangs at random places. Is there any way to
> identify when the script hangs and to resume it automatically. When I see
> that it is not responding i do ^Z (Ctrl -Z) to stop and then use fg command
> to start it again. I want to automate this.
>
>
As others have already suggested it is not a good idea to silently ignore
the errors,
so you should debug your script to understand where exactly the script
would hang.

You can get a trace of the script state when you press 'Ctrl+Z' by handling
the signal and making use of the 'inspect' module.

Consider the below sample code:

% cat signal.py

import signal
import time
import inspect

# Register function 'signal_handler' to handle the signal 'Ctrl+Z'
signal.signal(signal.SIGTSTP, signal_handler)

def signal_handler(signal, frame):
    print "You pressed Ctrl+Z\n";
    frame,filename,line_number,function_name,lines,index =
inspect.getouterframes(inspect.currentframe())[1]
    print(frame,filename,line_number,function_name,lines,index)



def signal_check():
    while (1):
        time.sleep(5)

if __name__ == '__main__':
    signal_check()


When the above script is running, pressing 'Ctrl+Z' would yield below
output and
the script would continue its execution.

% python signal.py
Hello
...
You pressed Ctrl+Z

(<frame object at 0x1a7ae770>, 'signal.py', 16, 'signal_check', ['
 time.sleep(5)\n'], 0)

Hello
Hello
...


The output from inspect:
frame,filename,line_number,function_name,lines,index =
inspect.getouterframes(inspect.currentframe())[1]
will give details like name of the function which resulted in call for
signal handler, line number etc.

Refer to the documentation of 'signal' module for more details on using
this module for signal handling.
https://docs.python.org/2/library/signal.html#module-signal

reg,
sateesh
_______________________________________________
BangPypers mailing list
BangPypers@python.org
https://mail.python.org/mailman/listinfo/bangpypers

Reply via email to