正在做c扩展

This commit is contained in:
shenjack 2022-07-07 18:28:29 +08:00
parent f1bf94cc55
commit d2e4c2f706
17 changed files with 307 additions and 86 deletions

3
.gitignore vendored
View File

@ -149,5 +149,4 @@ dmypy.json
other things/ other things/
.git-/ .git-/
try/cprint/cmake-build-debug *cmake-build-debug
try/c/cmake-build-debug

View File

@ -26,7 +26,6 @@ from Difficult_Rocket import client, server
from Difficult_Rocket.utils import tools from Difficult_Rocket.utils import tools
from Difficult_Rocket.utils.translate import tr from Difficult_Rocket.utils.translate import tr
class Game: class Game:
def __init__(self): def __init__(self):
# basic config # basic config

View File

@ -0,0 +1,19 @@
cmake_minimum_required(VERSION 3.22)
project(cprint VERSION 0.0.1 LANGUAGES C)
#
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_C_STANDARD 99)
#
add_compile_options(-O3)
add_compile_options(-Wall)
add_compile_options(-Werror)
#add_compile_options(-shared)
#add_compile_options(-o ../../cprint.dll)
# py3.8 path
include_directories(.)
include_directories(C:\\Users\\shenjack.SHENJACK-5600X\\AppData\\Local\\Programs\\Python\\Python38\\include\\.)
#
#add_executable(cprint cprint.c)
#
#add_executable(cprint cprint.c)
add_executable(py_cprint py_cprint.c)

View File

@ -0,0 +1,66 @@
import _winapi
import subprocess
import os
os.system('')
reset = '\033[0m'
print('A 000')
do = False
def rgb(r, g, b):
return 2, r, g, b
# i_list = list(range(30, 39, 1))
# # i_list = [39]
# j_list = list(range(40, 49, 1))
# # j_list = [49]
#
# for i in i_list:
# for j in j_list:
# print(f'\033[{i};{j}m{i}|{j} {reset}', end='|')
# print()
# print()
def color_print(*args):
args = [str(i) for i in args]
out = '|'.join(args)
line = ';'.join(args)
print(f'\033[{line}m{out}\033[0m')
if os.name == "nt":
from ctypes import windll
from ctypes.wintypes import BOOL, HANDLE, WORD
handle = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
kernel32 = windll.LoadLibrary("Kernel32.dll")
SetConsoleAttribute = kernel32.SetConsoleTextAttribute
SetConsoleAttribute.argtypes = (HANDLE, WORD)
SetConsoleAttribute.restype = BOOL
# FOREGROUND_INTENSITY|FOREGROUND_RED
res: bool = SetConsoleAttribute(handle, 5)
print(res)
string = "Hello World!"
_winapi.WriteFile(handle, string.encode("utf-8"), 0)
else:
pass
# exit(0)
color_print(94)
color_print(41, 93)
color_print(36, 40)
print()
color_print(48, *rgb(200, 100, 20), 34)
color_print(48, *rgb(255, 161, 72))
color_print(48, *rgb(255, 161, 72), 38, *rgb(1, 50, 255))
color_print(48, *rgb(178, 112, 50), 38, *rgb(98, 96, 167))
print()
color_print(48, *rgb(100, 10, 10), )
exit(0)

View File

@ -0,0 +1,11 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

View File

@ -0,0 +1,41 @@
import os
# include 目录
include_paths = ["C:\\Users\\shenjack.SHENJACK-5600X\\AppData\\Local\\Programs\\Python\\Python38\\include\\."]
# 编译选项
compile_options = {
"-shared": None,
"-O3": None,
"-Wall": None,
"-Werror": None,
"-o": "./py_cprint.dll"
}
include_command = "-I "
# 处理 include 目录命令
for path in include_paths:
include_command = "{}, {}".format(include_command, path)
else:
if len(include_paths) != 0:
include_command = include_command[:3] + include_command[4:]
compile_option_command = ""
# 处理编译选项
for option, key in compile_options.items():
if key is None:
compile_option_command = "{} {} ".format(compile_option_command, option)
else:
compile_option_command = "{} {} {}".format(compile_option_command, option, key)
print(include_command, compile_option_command)
compile_command = "gcc.exe ./py_cprint.c {}{}".format(include_command, compile_option_command)
print(compile_command)
os.system(compile_command)

View File

@ -0,0 +1,30 @@
//
// Created by shenjack on 2022/6/24.
//
//#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
int CcPrint(PyObject *self, PyObject *args, PyObject *kwargs){
char *print_str;
char *line_end = NULL; // 准备参数
static char *kwlist[] = {"some_stuf", "end", NULL}; // 准备参数列表
if(!PyArg_ParseTupleAndKeywords(args, kwargs, "ss", kwlist, &print_str, &line_end)){
return 0;
};
return 1;
};
// 如果你非得调用我·····
int main(){
printf("aaaa");
if(false){
CcPrint(PyLong_FromLong(1), PyLong_FromLong(1), PyLong_FromLong(1));
};
return 0;
};

View File

@ -0,0 +1,9 @@
from objprint import objprint
from ctypes import cdll
cprint = cdll.LoadLibrary("./cprint.dll")
# objprint(cprint)

View File

@ -0,0 +1,44 @@
//
// Created by shenjack on 2022/7/6.
//
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdint.h>
static PyObject *pycprint_print(PyObject *self, PyObject *args){
const char *text;
if(!PyArg_ParseTuple(args, "s", &text)){ // 解析 text
return NULL;
};
printf("%s", text);
Py_RETURN_NONE;
};
static PyObject *pycpint_printf(PyObject *self, PyObject *args, PyObject *kwargs){
PyObject *a;
if(!PyArg_ParseTuple(args, "O", &a)){
return NULL;
};
Py_ssize_t text_len = PyTuple_Size(args);
Py_RETURN_NONE;
};
static PyMethodDef PyCprintMethods[] = {
{"print", pycprint_print, METH_VARARGS, "直接使用c的printf输出"},
{"printf", (PyCFunction)(void(*))pycpint_printf, METH_VARARGS | METH_KEYWORDS,
"传入类似py print然后进行format的print"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef pycprintmodule = {
PyModuleDef_HEAD_INIT,
"pycprint",
"直接调用c的printf",
-1,
PyCprintMethods
};
PyMODINIT_FUNC PyInit_pycprint(void){
return PyModule_Create(&pycprintmodule);
}

View File

@ -0,0 +1,9 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
from build import pycprint
pycprint.print("aaa\n")

View File

@ -0,0 +1,7 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
def print(text: str) -> None: ... # 直接调用fprint

View File

@ -0,0 +1,30 @@
from setuptools import setup, Extension
import shutil
import os
pycprint = Extension('pycprint',
sources=['py_cprint.c'])
setup(name='PyCprint',
version='0.0.1',
author='shenjack',
author_email='3695888@qq.com',
description='这是一个用于直接调用c的printf的库',
ext_modules=[pycprint])
def dir_not_temp(path: str):
return path.find('temp') and os.path.isdir(os.path.join('build', path))
build_dir = os.listdir('./build')
build_dir = list(filter(dir_not_temp, build_dir))
# 用列表推导式把 是文件夹 且 名字里没有 temp 的抽出来
print(build_dir)
os.chdir('build')
# 把运行路径迁移过去方便copy
for build in build_dir:
copy = os.listdir(build)
shutil.copy(os.path.join(build, copy[0]), './')

Binary file not shown.

View File

@ -25,16 +25,24 @@ DEBUG = 10
NOTSET = 0 NOTSET = 0
""" """
DETAIL = 5
class LogFileCache: class LogFileCache:
"""日志文件缓存""" """日志文件缓存"""
def __init__(self, file_name: str = 'logs//log.log', flush_time: Optional[Union[int, float]] = 1, cache_entries_num: int = 10): def __init__(self, file_name: str = 'logs//log.log', flush_time: Optional[Union[int, float]] = 1, log_cache_lens_max: int = 10):
"""
@param file_name: 日志文件名称
@param flush_time: 刷新日志缓存写入文件的时长间隔
@param log_cache_lens_max: 日志缓存在自动写入前的最大缓存长度
"""
# 配置相关 # 配置相关
self._logfile_name = file_name # log 文件名称 self._logfile_name = file_name # log 文件名称
self.flush_time = flush_time # 缓存刷新时长 self.flush_time = flush_time # 缓存刷新时长
self.cache_entries_num = cache_entries_num self.cache_entries_num = log_cache_lens_max
# 写入缓存数 # 写入缓存数
self.cache_count = 0 self.cache_count = 0
# 日志缓存表 # 日志缓存表
@ -45,6 +53,7 @@ class LogFileCache:
self.threaded_write = threading.Timer(1, self._log_file_time_write) self.threaded_write = threading.Timer(1, self._log_file_time_write)
def end_thread(self): def end_thread(self):
"""结束日志写入进程,顺手把目前的缓存写入"""
self.thread_lock.acquire(blocking=True) self.thread_lock.acquire(blocking=True)
self.threaded_write.cancel() self.threaded_write.cancel()
if self.cache_count: if self.cache_count:
@ -66,7 +75,6 @@ class LogFileCache:
def _log_file_time_write(self) -> None: def _log_file_time_write(self) -> None:
"""使用 threading.Timer 调用的定时写入日志文件的函数""" """使用 threading.Timer 调用的定时写入日志文件的函数"""
with self.with_thread_lock: with self.with_thread_lock:
...
if self.cache_count == 0: if self.cache_count == 0:
return None return None
... ...
@ -93,7 +101,7 @@ class Logger:
else: else:
... ...
def make_log(self, level: str, def make_log(self, level: int,
*values: object, *values: object,
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
@ -104,61 +112,45 @@ class Logger:
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
flush: Optional[bool] = False) -> None: flush: Optional[bool] = False) -> None:
self.make_log(level='detail', *values, sep=sep, end=end, flush=flush) self.make_log(level=DETAIL, *values, sep=sep, end=end, flush=flush)
def debug(self, def debug(self,
*values: object, *values: object,
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
flush: Optional[bool] = False) -> None: flush: Optional[bool] = False) -> None:
... self.make_log(level=DEBUG, *values, sep=sep, end=end, flush=flush)
def info(self, def info(self,
*values: object, *values: object,
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
flush: Optional[bool] = False) -> None: flush: Optional[bool] = False) -> None:
... self.make_log(level=INFO, *values, sep=sep, end=end, flush=flush)
def warning(self, def warning(self,
*values: object, *values: object,
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
flush: Optional[bool] = False) -> None: flush: Optional[bool] = False) -> None:
... self.make_log(level=WARNING, *values, sep=sep, end=end, flush=flush)
def error(self, def error(self,
*values: object, *values: object,
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
flush: Optional[bool] = False) -> None: flush: Optional[bool] = False) -> None:
... self.make_log(level=ERROR, *values, sep=sep, end=end, flush=flush)
def fatal(self, def fatal(self,
*values: object, *values: object,
sep: Optional[str] = ' ', sep: Optional[str] = ' ',
end: Optional[str] = '\n', end: Optional[str] = '\n',
flush: Optional[bool] = False) -> None: flush: Optional[bool] = False) -> None:
... self.make_log(level=FATAL, *values, sep=sep, end=end, flush=flush)
# class LoggerManager: logger_configs = {
# """shenjack牌logger"""
#
# def __init__(self):
# self.configs = {}
#
# def add_config(self, name: str, config: dict) -> dict:
# self.configs[name] = config
# return self.configs
#
# def get_logger(self, name: str = 'root', config: dict = None) -> Logger:
# """相当于 logging.getLogger(name='root')"""
# if config is not None:
# self.add_config(name, config)
# return Logger(config=self.configs)
global_configs = {
'root': { 'root': {
'level': DEBUG, 'level': DEBUG,
'color': { 'color': {
@ -171,3 +163,24 @@ global_configs = {
...: ... ...: ...
} }
} }
def add_dict_config_to_global(some_dict: dict, name: str) -> dict:
"""
@param some_dict: 一个你丢进来的 logger 设置
@param name: 这个 logger 设置的名称
@return: 修改过的 logger 配置
"""
logger_configs[name] = some_dict
return logger_configs
def add_kwargs_to_global(**kwargs) -> dict:
"""
@param kwargs:
@return:
"""
...

View File

@ -1,12 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie
# All rights reserved
# -------------------------------
"""
writen by shenjackyuanjie
mail: 3695888@qq.com
github: @shenjackyuanjie
gitee: @shenjackyuanjie
"""

View File

@ -1,12 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2021-2022 by shenjackyuanjie
# All rights reserved
# -------------------------------
"""
writen by shenjackyuanjie
mail: 3695888@qq.com
github: @shenjackyuanjie
gitee: @shenjackyuanjie
"""

View File

@ -1,32 +0,0 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2021 by shenjackyuanjie
# All rights reserved
# -------------------------------
"""
writen by shenjackyuanjie
mail: 3695888@qq.com
github: @shenjackyuanjie
gitee: @shenjackyuanjie
"""
"""
this is a test of modding in Difficult Rocket
just a test
只是一个DR的mod测试
"""
# from libs
import semver
# from DR
from Difficult_Rocket import semver_game_version
from Difficult_Rocket.mods import MODInfo, semver_loader_version
mod_info = MODInfo(name="test mod",
version=semver.VersionInfo.parse("0.0.1"),
write_version=semver_game_version,
write_loader_version=semver_loader_version)
print(mod_info.serialize())