0
while True:
    try:
        # send some mail
        time.sleep(hours*60*60)
    except:
        time.sleep(60)

This script is supposed to send an email every x hours. And it does. If it fails, it should wait a minute and try again. I tested it with hours set to 0.01 (36 seconds), and it worked, even when I turned wifi off and back on. But when I set it to 2 hours, and waited, nothing happened. The Pythonw process just disappeared.

David
  • 139
  • 2
  • 8

1 Answers1

0

You should rename it to .py and watch the console output.

Or, even better, set up logging of unhandled exceptions (see below). In general, you must use logging to report on the script's progress if it's going to run unattended: there's simply no other way for you to know what is happening with it!

E.g. when the script starts a very long wait, you can report at which moment it starts waiting and for how long - that will clarify things for you.

The following is how I set up logging in my scripts that are to be run in background for extended time:

# set up logging #####################################
import sys,logging,logging.handlers,os.path
logfile = os.path.splitext(os.path.basename(sys.argv[0]))[0]+".log"
l = logging.getLogger()
l.setLevel(logging.DEBUG)
f = logging.Formatter('%(asctime)s %(process)d:%(thread)d %(name)s %(levelname)-8s %(message)s')
h=logging.StreamHandler(sys.stdout)
h.setLevel(logging.NOTSET)
h.setFormatter(f)
l.addHandler(h)
h=logging.handlers.RotatingFileHandler(logfile,maxBytes=1024**2,backupCount=1)
h.setLevel(logging.NOTSET)
h.setFormatter(f)
l.addHandler(h)
del h,f
#hook to log unhandled exceptions
def excepthook(type,value,traceback):
    logging.error("Unhandled exception occured",exc_info=(type,value,traceback))
    #Don't need another copy of traceback on stderr
    if old_excepthook!=sys.__excepthook__:
        old_excepthook(type,value,traceback)
old_excepthook = sys.excepthook
sys.excepthook = excepthook
del excepthook,logfile
# ####################################################
ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • I don't get it. It seems to be working now... I wonder if it will still work when I disable logging. – David Mar 25 '17 at 19:05
  • It broke after a few hours of sending mail. No errors in the log. Last updated an hour and 30 minutes ago. The python process is still running, but the script just isn't doing anything. – David Mar 25 '17 at 21:28
  • I take that back. It's working. Just a slight delay (20-30 minutes). That's fine though. Accepting answer. – David Mar 25 '17 at 21:37
  • @David If you need to loop at constant rate, you should calculate the time to sleep from the next reference point - not doing that is likely what's causing the delay: http://stackoverflow.com/questions/26774186/looping-at-a-constant-rate-with-high-precision-for-signal-sampling/26774385#26774385 – ivan_pozdeev Mar 26 '17 at 06:17