You could install an exception hook, by assigning a custom function to the sys.excepthook
handler. The function is called whenever there is a unhandled exception (so one that exits the interpreter).
import sys
def myexcepthook(type, value, tb):
import traceback
from email.mime.text
import MIMEText
from subprocess
import Popen, PIPE
tbtext = ''.join(traceback.format_exception(type, value, tb))
msg = MIMEText("There was a problem with your program:\n\n" + tbtext)
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "Program exited with a traceback."
p = Popen(["/usr/sbin/sendmail", "-t"], stdin = PIPE)
p.communicate(msg.as_string())
sys.excepthook = myexcepthook
You can surrond your whole program with a try/except
block, which is not very beautiful I find. Another way is to run your python script in a .sh
file and execute this:
#!/bin/bash while true do python your_script.py if $ ? != 0 then sendmail "blabla" "see the doc" "for arguments" fi done
You should try like this:
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
If an exception is raised during execution of the exit handlers, a traceback is printed (unless SystemExit is raised) and the exception information is saved. After all exit handlers have had a chance to run, the last exception to be raised is re-raised.,At normal program termination (for instance, if sys.exit() is called or the main module’s execution completes), all functions registered are called in last in, first out order. The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later.,Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register(). It is possible to register the same function and arguments more than once.,The following simple example demonstrates how a module can initialize a counter from a file when it is imported and save the counter’s updated value automatically when the program terminates without relying on the application making an explicit call into this module at termination.
try:
with open('counterfile') as infile:
_count = int(infile.read())
except FileNotFoundError:
_count = 0
def incrcounter(n):
global _count
_count = _count + n
def savecounter():
with open('counterfile', 'w') as outfile:
outfile.write('%d' % _count)
import atexit
atexit.register(savecounter)
def goodbye(name, adjective):
print('Goodbye %s, it was %s to meet you.' % (name, adjective))
import atexit
atexit.register(goodbye, 'Donny', 'nice')
# or:
atexit.register(goodbye, adjective = 'nice', name = 'Donny')
import atexit
@atexit.register
def goodbye():
print('You are now leaving the Python sector.')
PythonAnywhere consoles can run for a long time, but we do occasionally have to bounce our servers for maintenance. So, while you can usually keep a console program running for a long time, you will occasionally find it resets itself.,If the error you see in the log is something like "permission denied", it's probably because you've entered the path to a Python script in the "Command" field instead of a command. Remember, you need to specify,...then you can use the same command to activate it before running it. Let's say that your virtualenv is called my-env and you want to run the script located at /home/yourusername/something/script.py -- the command to do that in the always-on task "command" input would be this:,If you're printing stuff out in an always-on task, it might not appear in the log in a timely fashion. This is because when Python is sending print output to something that is not a console -- for example, a file -- it keeps it in a buffer, and only flushes it out to the real output when the buffer gets full.
To set up an always-on task, you just need to enter the full command to run it into the input field -- for example,
python3 .6 / home / yourusername / a - directory / a - script.py
Virtualenvwrapper is the system that provides the mkvirtualenv
and workon
commands, so if you used the former to create your virtualenv and use the latter
when you want to do stuff using it, you can use them for your always-on task
too. Let's say that your virtualenv is called my-env
and you want to run the
script located at /home/yourusername/something/script.py
-- the command to do
that in the always-on task "command" input would be this:
workon my - env && python / home / yourusername / something / script.py
If you use Python 3's built-in venv
module -- that is, you did something like
this to create it:
python3 .6 - m venv my - env
...then you can use the same command to activate it before running it.
Let's say that your virtualenv is called my-env
and you want to run the
script located at /home/yourusername/something/script.py
-- the command to do
that in the always-on task "command" input would be this:
source / home / yourusername / my - env / bin / activate && python / home / yourusername / something / script.py
If the error you see in the log is something like "permission denied", it's probably because you've entered the path to a Python script in the "Command" field instead of a command. Remember, you need to specify
python3 .6 / path / to / script.py