0

出于某种原因,当我的程序关闭时,退出处理程序没有被激活。因此,我的程序没有按照. 为什么退出时不激活?enterexit_handleratexit.register(exit_handler)

蟒蛇代码:

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)

命令提示符输入:

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

结果文件 (dicelog.txt) 内容:

{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}

我对 Python 比较陌生,所以请温柔一点。在此先感谢您的帮助。

4

0 回答 0