pocketpy/prebuild.py
2024-02-18 10:58:48 +08:00

42 lines
1.1 KiB
Python

import os
def generate_python_sources():
sources = {}
for file in sorted(os.listdir("python")):
if not file.endswith(".py"):
continue
key = file.split(".")[0]
with open("python/" + file) as f:
value = f.read()
value = value.encode('utf-8').hex()
new_value = []
for i in range(0, len(value), 2):
new_value.append("\\x" + value[i:i+2])
sources[key] = "".join(new_value)
header = '''#pragma once
// generated by prebuild.py
#include <map>
#include <string>
namespace pkpy{
inline static std::map<std::string, const char*> kPythonLibs = {
'''
for key, value in sources.items():
CHAR_LIMIT = 5000
value = ['"' + value[i:i+CHAR_LIMIT] + '" ' for i in range(0, len(value), CHAR_LIMIT)]
value = ''.join(value)
header += ' '*8 + '{"' + key + '", ' + value + '},'
header += '\n'
header += '''
};
} // namespace pkpy
'''
return header
# use LF line endings instead of CRLF
with open("include/pocketpy/_generated.h", "wt", encoding='utf-8', newline='\n') as f:
f.write(generate_python_sources())