For some reason, when my program is closing, the exit handler is not being activated. Therefore, my program is not logging the date/time of file close or hitting enter
twice (to prepare the file for the program's next run, keep things neat) as dictated in exit_handler
. Why isn't atexit.register(exit_handler)
activating on exit?
Python Code:
from random import randint
import datetime
import atexit
import sys
def update_log(x):
log = open("dicelog.txt","a",encoding="utf-8")
log.write(x)
log.write("\n")
log.close()
while True:
d_to_roll = input("xdx: ")
if d_to_roll == "close" or d_to_roll == "exit" or d_to_roll == "end":
sys.exit()
else:
ls_to_parse = d_to_roll.split("d")
parsed_ls = [ int(x) for x in ls_to_parse ]
num_rolls = parsed_ls[0]
d_type = parsed_ls[1]
d_rolls = {}
for i in range(num_rolls):
d_rolls[i+1] = randint(1,d_type)
x = (str(d_rolls))
print(x,"\n")
update_log(x)
def exit_handler():
now = str(datetime.datetime.now()) + "\n\n"
update_log(now)
atexit.register(exit_handler)
Command Prompt Inputs:
C:\Users\Fiona Murphey\Desktop\D&D>python RPGDice.py
xdx: 5d20
{1: 12, 2: 11, 3: 15, 4: 16, 5: 9}
xdx: 3d6
{1: 6, 2: 5, 3: 3}
xdx: 2d4
{1: 3, 2: 3}
xdx: 8d12
{1: 4, 2: 9, 3: 8, 4: 5, 5: 3, 6: 5, 7: 11, 8: 4}
xdx: close
C:\Users\Fiona Murphey\Desktop\D&D>python RPGDice.py
xdx: 7d10
{1: 8, 2: 10, 3: 1, 4: 6, 5: 7, 6: 8, 7: 3}
xdx: 2d10
{1: 7, 2: 8}
xdx: 8d6
{1: 3, 2: 6, 3: 3, 4: 1, 5: 1, 6: 1, 7: 2, 8: 5}
xdx: exit
Resulting File (dicelog.txt) Contents:
{1: 12, 2: 11, 3: 15, 4: 16, 5: 9}
{1: 6, 2: 5, 3: 3}
{1: 3, 2: 3}
{1: 4, 2: 9, 3: 8, 4: 5, 5: 3, 6: 5, 7: 11, 8: 4}
{1: 8, 2: 10, 3: 1, 4: 6, 5: 7, 6: 8, 7: 3}
{1: 7, 2: 8}
{1: 3, 2: 6, 3: 3, 4: 1, 5: 1, 6: 1, 7: 2, 8: 5}
I am relatively new to Python, so please be gentle. Thanks in advance for the help.