Python的自制没用扩展
2026-08-05 12:31:51
发布于:浙江
主文件“ASCII_api.py”
version_info = {
'version': '1.2.0 zh_cn',
"name": "ASCII Art API for Python",
"date": "2026-08-05",
"Error_logs": 60, # 错误日志保存天数
"log_logs": 30 # 日志保存天数
}
import time
import os
import json
from pathlib import Path
import random
from ASCII_art_num import ASCII_ART_NUM
# 获取当前时间戳和格式化时间
code_opentime_ms = time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime())
code_opentime = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
# 新建日志文件夹
log_dir = Path("Python_api_logs")
log_dir.mkdir(exist_ok=True)
# 删除超过1个月的日志文件
for file in log_dir.glob("*.log"):
if time.time() - file.stat().st_mtime > version_info["log_logs"] * 24 * 60 * 60: # 根据配置的日志保存天数
file.unlink()
# 删除超过2个月的错误日志文件
for file in log_dir.glob("*.log_error.txt"):
if time.time() - file.stat().st_mtime > version_info["Error_logs"] * 24 * 60 * 60: # 根据配置的错误日志保存天数
file.unlink()
pi_float = 3.14159265358979323846264338327950288419716939937510
pi_string = "3.14159265358979323846264338327950288419716939937510"
def get_time():
return time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime())
def get_color_code(color_name):
color_codes = {
"black": 30,
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"magenta": 35,
"cyan": 36,
"white": 37,
"reset": 0
}
return color_codes.get(color_name.lower(), 0) # 默认返回重置代码
def write_log(text, log_file=f'[{code_opentime}].log'):
# 将日志写入文件夹
try:
text = str(text)
with open(log_dir / log_file, 'a', encoding='utf-8') as f:
f.write(f"[{get_time()}] {text}\n")
except Exception as e:
print(f"// [{get_time()}] 写入日志时发生错误: {e}")
with open(log_dir / f'[{code_opentime}].log_error.txt', 'a', encoding='utf-8') as f:
f.write(f"[{get_time()}] 写入日志时发生错误: {e}\n")
def del_all_logs():
for file in log_dir.glob("*.log"):
file.unlink()
write_log("已删除所有日志文件")
def del_allerror_logs():
for file in log_dir.glob("*.log_error.txt"):
file.unlink()
write_log("已删除所有错误日志文件")
def del_logs(log_file=f'[{code_opentime}].log'):
try:
log_path = log_dir / log_file
if log_path.exists():
log_path.unlink()
write_log(f"已删除日志文件: {log_file}")
else:
write_log(f"日志文件不存在: {log_file}")
except Exception as e:
print(f"// [{get_time()}] 删除日志文件时发生错误: {e}")
write_log(f"删除日志文件时发生错误: {e}")
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
write_log("控制台已清除")
def ASCII_ART_TEXT(text):
from ASCII_art_num import ASCII_ART_NUM
out = ["", "", "", "", "", "","",""]
for char in text:
try:
glyph = ASCII_ART_NUM.get(char, ASCII_ART_NUM.get(" "))
if not glyph:
continue
for line_index, line in enumerate(glyph):
out[line_index] += line + " "
except Exception as e:
write_log(f"Error processing character '{char}': {e}")
print(f"[{get_time()}] Error processing character '{char}': {e}")
continue
out = [line.rstrip() for line in out]
write_log(f"ASCII艺术字已生成: {text}")
return "\n".join(out)
class transcode: # 转换
# 二进制转十进制
@staticmethod
def binary_to_decimal(binary_str):
try:
return int(binary_str, 2)
except ValueError:
raise ValueError("输入的字符串不是有效的二进制数")
# 十进制转二进制
@staticmethod
def decimal_to_binary(decimal_num):
if not isinstance(decimal_num, int) or decimal_num < 0:
raise ValueError("输入必须是非负整数")
return bin(decimal_num)[2:]
# ASCII转二进制
@staticmethod
def ascii_to_binary(ascii_str):
return ''.join(format(ord(char), '08b') for char in ascii_str)
# 二进制转ASCII
@staticmethod
def binary_to_ascii(binary_str):
if len(binary_str) % 8 != 0:
raise ValueError("二进制字符串长度必须是8的倍数")
ascii_str = ''
for i in range(0, len(binary_str), 8):
byte = binary_str[i:i+8]
ascii_str += chr(int(byte, 2))
return ascii_str
# 十进制转ASCII
@staticmethod
def decimal_to_ascii(decimal_num):
if not isinstance(decimal_num, int) or decimal_num < 0:
raise ValueError("输入必须是非负整数")
return chr(decimal_num)
# ASCII转十进制
@staticmethod
def ascii_to_decimal(ascii_str):
if len(ascii_str) != 1:
raise ValueError("输入必须是单个字符")
return ord(ascii_str)
def get_current_time():
return time.time()
def sort(inp, reverse=False):
for i in range(len(inp)):
res = 0
for j in range(i + 1, len(inp)):
if reverse:
if inp[i] < inp[j]:
inp[i], inp[j] = inp[j], inp[i]
res += 1
else:
if inp[i] > inp[j]:
inp[i], inp[j] = inp[j], inp[i]
res += 1
if res == 0:
break
return inp
def slow_print(text, delay=0, enter=True, flush_=True):
try:
text = str(text)
delay = float(delay)
if delay <= 0:
print(text, end='', flush=flush_)
else:
for char in text:
print(char, end='', flush=flush_)
time.sleep(delay)
if enter:
print()
return True
except (ValueError, TypeError) as e:
print(f"// [{get_time()}] 发生错误: {e} >>>")
write_log(f"slow_print error: {e}")
return False
def random_num(inp, jingdu):
n=100
if jingdu < 0:
jingdu = 0
if jingdu > 10:
jingdu = 10
if inp <= 0:
return False
if inp >=100:
return True
for i in range(jingdu):
n*=10
random_number = random.randint(1, n)
for i in range(jingdu):
random_number /= 10
if random_number <= inp:
return True
else:
return False
def game_except(e, script_path='None'):
import tkinter as tk
import time
import subprocess
time.sleep(1)
write_log(f"{str(script_path)}发生错误: {str(e)}")
clear_console()
root = tk.Tk()
root.title(f"mine game {script_path.name} 错误提示")
root.geometry("700x250")
label = tk.Label(root, text="错误", font=("Arial", 16))
label.pack(pady=20)
error_message = f"发生错误: {str(e)}"
error_label = tk.Label(root, text=error_message, font=("Arial", 12), fg="red")
error_label.pack(pady=10)
def restart_program():
python = subprocess.Popen(['python', __file__])
root.destroy()
restart_button = tk.Button(root, text="重启程序", command=restart_program)
restart_button.pack(pady=10)
exit_button = tk.Button(root, text="退出程序", command=root.destroy)
exit_button.pack(pady=10)
root.mainloop()
def game_except_text(e, script_path='None'):
clear_console()
write_log(f"{str(script_path)}发生错误: {str(e)}")
slow_print(f'// Exception: {str(e)} >>>', 0.05)
slow_print(f'// Error location: {script_path} >>>', 0.05)
def say_PASS(color="green"):
print(f"\033[{get_color_code(color)}m{ASCII_ART_NUM['PASS']}\033[0m")
def say_FAIL(color="red"):
print(f"\033[{get_color_code(color)}m{ASCII_ART_NUM['FAIL']}\033[0m")
def get_version():
write_log(f"获取程序版本: {version_info['version']}")
return version_info['version']
def write_exit_log():
write_log(f"程序关闭,版本: {get_version()}, 关闭时间: {get_time()}")
write_log(f"程序启动,版本: {get_version()}")
script_path = Path(__file__).resolve() # 当前.py文件的绝对路径
script_dir = script_path.parent # 当前.py所在文件夹
write_log(f"当前脚本路径: {script_path}")
clear_console()
ASCII艺术字对照表“ASCII_art_num.py”
ASCII_ART_NUM = {
" ": [
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
],
"(": [
" __ ",
" / / ",
" / / ",
" | | ",
" \ \ ",
" \_\ ",
" ",
" "
],
")": [
" __ ",
" \ \ ",
" \ \ ",
" | | ",
" / / ",
" /_/ ",
" ",
" "
],
"-": [
" ",
" ",
" ______ ",
"|______|",
" ",
" ",
" ",
" "
],
"+": [
" ",
" __ ",
" / \ ",
" | () | ",
" \__/ ",
" ",
" ",
" "
],
"_": [
" ",
" ",
" ",
" ",
" ",
" ",
" ______ ",
"|______|"
],
"!": [
" _ ",
" | | ",
" | | ",
" | | ",
" |_| ",
" (_) ",
" ",
" "
],
"?" : [
" ____ ",
" / __ \ ",
"| | | |",
" \/ / / ",
" /_/ ",
" (_) ",
" ",
" "
],
"0": [
" _____ ",
"/ _ \ ",
"| | | | ",
"| | | | ",
"| |_| | ",
"\_____/ ",
" ",
" "
],
"1": [
" ___ ",
" /_ | ",
" | | ",
" | | ",
" _| |_ ",
" |_____|",
" ",
" "
],
"2": [
" ____ ",
" / _ \ ",
"/_// / ",
" / / ",
" / /___ ",
"/_____/ ",
" ",
" "
],
"3": [
" _____ ",
"/ _ \ ",
" / / ",
" \ \ ",
" __\ \ ",
" \____/ ",
" ",
" "
],
"4": [
" __ ",
" / |",
" / /| |",
" / /_| |",
"/____ |",
" |_|",
" ",
" "
],
"5": [
" _____ ",
"| ___| ",
"| |__ ",
"| __\ ",
"____| | ",
"\____/ ",
" ",
" "
],
"6": [
" _____ ",
"/ ___| ",
"| |__ ",
"| __ \ ",
"| |_| | ",
"\____/ ",
" ",
" "
],
"7": [
" _____ ",
"|__ / ",
" / / ",
" / / ",
"/ / ",
"\_/ ",
" ",
" "
],
"8": [
" _____ ",
"/ _ \ ",
"| |_| | ",
"| _ | ",
"| |_| | ",
" \____/ ",
" ",
" "
],
"9": [
" _____ ",
"/ _ \ ",
"| |_| | ",
" \__ | ",
"|\__| | ",
"\____/ ",
" ",
" "
],
".": [
" ",
" ",
" ",
" ",
" __ ",
" |_| ",
" ",
" "
],
"A": [
" ___ ",
" / _ \ ",
"/ /_\ \ ",
"| _ | ",
"| | | | ",
"\_| |_/ ",
" ",
" "
],
"B": [
"______ ",
"| ___ \ ",
"| |_/ / ",
"| ___ \ ",
"| |_/ / ",
"\____/ ",
" ",
" "
],
"C": [
" _____ ",
"/ __ \ ",
"| / \/ ",
"| | ",
"| \__/\ ",
" \____/ ",
" ",
" "
],
"D": [
" ____ ",
"| \ ",
"| |\ \ ",
"| | | | ",
"| |/ / ",
"|____/ ",
" ",
" "
],
"E": [
" _____ ",
"| ___| ",
"| |__ ",
"| __| ",
"| |___ ",
"\____/ ",
" ",
" "
],
"F": [
" _____ ",
"| ___| ",
"| |__ ",
"| __| ",
"| | ",
"\_| ",
" ",
" "
],
"G": [
" _____ ",
"/ __ \ ",
"| / \/ ",
"| | _ ",
"| \_/ | ",
" \__/\| ",
" ",
" "
],
"H": [
" _ _ ",
"| | | | ",
"| |_| | ",
"| _ | ",
"| | | | ",
"\_| |_/ ",
" ",
" "
],
"I": [
" _____ ",
"|_ _| ",
" | | ",
" | | ",
" _| |_ ",
" \___/ ",
" ",
" "
],
"J": [
" ___ ",
" |_ | ",
" | | ",
" | | ",
"/\__/ / ",
"\____/ ",
" ",
" "
],
"K": [
" _ __ ",
"| | / / ",
"| |/ / ",
"| \ ",
"| |\ \ ",
"\_| \_/ ",
" ",
" "
],
"L": [
" _ ",
"| | ",
"| | ",
"| | ",
"| |___ ",
"\____/ ",
" ",
" "
],
"M": [
"___ ___",
"| \/ |",
"| . . |",
"| |\/| |",
"| | | |",
"\_| |_/",
" ",
" "
],
"N": [
" _ _ ",
"| \ | | ",
"| \| | ",
"| . ` | ",
"| |\ | ",
"\_| \_/ ",
" ",
" "
],
"O": [
" _____ ",
"/ _ \ ",
"| | | | ",
"| | | | ",
"| |_| | ",
" \___/ ",
" ",
" "
],
"P": [
"______ ",
"| ___ \ ",
"| |_/ / ",
"| __/ ",
"| | ",
"\_| ",
" ",
" "
],
"Q": [
" _____ ",
"/ _ \ ",
"| | | | ",
"| | | | ",
"| \_/ | ",
" \__\_\ ",
" ",
" "
],
"R": [
"______ ",
"| ___ \ ",
"| |_/ / ",
"| / ",
"| |\ \ ",
"\_| \_| ",
" ",
" "
],
"S": [
" _____ ",
"/ ___| ",
"\ `--. ",
" `--. \ ",
"/\__/ / ",
"\____/ ",
" ",
" "
],
"T": [
" _____ ",
"|_ _| ",
" | | ",
" | | ",
" | | ",
" \_/ ",
" ",
" "
],
"U": [
" _ _ ",
"| | | | ",
"| | | | ",
"| | | | ",
"| |_| | ",
" \___/ ",
" ",
" "
],
"V": [
" _ _ ",
"| | | | ",
"| | | | ",
"\ \,/ / ",
" \ | / ",
" \_/ ",
" ",
" "
],
"W": [
" _ _ ",
"| | | |",
"| | | |",
"| |/\| |",
"\ /\ /",
" \/ \/ ",
" ",
" "
],
"X": [
"__ __ ",
"\ \ / / ",
" \ V / ",
" / \ ",
"/ /^\ \ ",
"\/ \/ ",
" ",
" "
],
"Y": [
"__ __ ",
"\ \ / / ",
" \ V / ",
" \ / ",
" | | ",
" \_/ ",
" ",
" "
],
"Z": [
" _____ ",
"|__ / ",
" / / ",
" / / ",
"/ /___ ",
"\_____| ",
" ",
" "
],
"a": [
" ",
" ",
" ___ ",
" / _ \ ",
"| (_) | ",
" \___,\ ",
" ",
" "
],
"b": [
" _ ",
"| | ",
"| |__ ",
"| '_ \ ",
"| |_) |",
"|_.__/ ",
" ",
" "
],
"c": [
" ",
" ",
" ___ ",
" / __\ ",
"| (___ ",
" \___/ ",
" ",
" "
],
"d": [
" _ ",
" | |",
" __| |",
" / _` |",
"| (_| |",
" \__,_|",
" ",
" "
],
"e": [
" ",
" ",
" ___ ",
" //_\ \ ",
"| ____| ",
" \____/ ",
" ",
" "
],
"f": [
" __ ",
"__/ _\ ",
"|_ __| ",
" | | ",
" | | ",
" \_| ",
" ",
" "
],
"g": [
" ",
" ",
" __ _ ",
" / _` |",
"| (_| |",
" \__, |",
" |___/ ",
" ",
" "
],
"h": [
" _ ",
"| | ",
"| |__ ",
"| '_ \ ",
"| | | |",
"|_| |_|",
" ",
" "
],
"i": [
" _ ",
" (_) ",
" _ ",
" | | ",
" | | ",
" |_| ",
" ",
" "
],
"j": [
" _ ",
" (_)",
" _ ",
" | |",
" | |",
" | |",
" /\_/ /",
" \___/ "
],
"k": [
" _ ",
"| | ",
"| | __ ",
"| |/ / ",
"| < ",
"|_|\_\ ",
" ",
" "
],
"l": [
" _ ",
" | | ",
" | | ",
" | | ",
" | |_|`",
" \____/",
" ",
" "
],
"m": [
" ",
" ",
" _ __ ___ ",
"| '_ ` _ \ ",
"| | | | | |",
"|_| |_| |_|",
" ",
" "
],
"n": [
" ",
" ",
" _ __ ",
"| '_ \ ",
"| | | |",
"|_| |_|",
" ",
" "
],
"o": [
" ",
" ",
" ___ ",
" / _ \ ",
"| (_) |",
" \___/ ",
" ",
" "
],
"p": [
" ",
" ",
" _ __ ",
"| '_ \ ",
"| |_) |",
"| .__/ ",
"| | ",
"\_| "
],
"q": [
" ",
" ",
" __ _ ",
" / _` |",
"| (_| |",
" \__, |",
" | |",
" \_|"
],
"r": [
" ",
" ",
" _ __ ",
"| '__\ ",
"| | ",
"|_| ",
" ",
" "
],
"s": [
" ",
" ",
" ___ ",
" / _ \ ",
" \__ \ ",
" \___/ ",
" ",
" "
],
"t": [
" _ ",
" | | ",
"_| |_ ",
"\_ __| ",
" | |_ ",
" \__| ",
" ",
" "
],
"u": [
" ",
" ",
" _ _ ",
"| | | |",
"| |_| |",
" \___,|",
" ",
" "
],
"v": [
" ",
" ",
" _ _ ",
"/ | | |",
"`\ V / ",
" \_/ ",
" ",
" "
],
"w": [
" ",
" ",
" _ _ ",
"/ | | \ ",
"| |/\| | ",
"\__/\__/ ",
" ",
" "
],
"x": [
" ",
" ",
"__ __ ",
"\ \_/ / ",
" | _ | ",
"/_/ \_\ ",
" ",
" "
],
"y": [
" ",
" ",
" _ _ ",
"| | | |",
"| |_| |",
" \__ |",
",._/ / ",
"\___/ "
],
"z": [
" ",
" ",
" _____ ",
"|__ / ",
" / / ",
" /_/__ ",
"\____/ ",
" "
],
}
没什么用就是了
这里空空如也















有帮助,赞一个