用cython把.py编译成 .exe(踩坑)
0,环境
windows10
mingw64
python37
pip install cython
并且检验mingw64路径
1,t.py
import os
print(os.getcwd())
input("...")
2,生成t.c
cython t.py --embed
–embed:生成main主函数入口
3,bug之一
如果你勇敢的直接编译:
gcc t.c -I D:\python\include -L D:\python\libs
解决方案:
#ifndef Py_PYPORT_H
#define Py_PYPORT_H
#if defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
#define CONFIG_WIN32
#endif
#if defined(WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(EMULATE_INTTYPES)
#define EMULATE_INTTYPES
#endif
#include "pyconfig.h" /* include for defines */
#ifndef EMULATE_INTTYPES
//#include <inttypes.h>
//#else
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
#ifdef CONFIG_WIN32
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else /* other OS */
typedef signed long long int64_t;
typedef unsigned long long uint64_t;
#endif /* other OS */
#endif /* EMULATE_INTTYPES */
//解决UINT64_C没定义的问题
#ifndef INT64_C
#define INT64_C(c) (c##LL)
#define UINT64_C(c) (c##ULL)
#endif
// #include <inttypes.h>
这是pyport.h的修改,不懂C语言的就对比修改一下就行
4,bug之二
(建议大家改用x86_64-w64-mingw32-gcc-8.1.0.exe, 也在gcc同一目录)
5, bug之三
执行:
x86_64-w64-mingw32-gcc-8.1.0 -mconsole -DSIZEOF_VOID_P=8 -DMS_WIN64 t.c -I D:/Python/include -L D:/Python/libs -l python37 -o t
结果提示:没有Winmain程序入口…
解决方案:
在t.c中查找wmain,将其改成main
6,大概大功告成了
x86_64-w64-mingw32-gcc-8.1.0 -mconsole -DSIZEOF_VOID_P=8 -DMS_WIN64 t.c -I D:/Python/include -L D:/Python/libs -l python37 -o t
你会发现在该目录下生成了t.exe
7,简化工作
makec.py:
import os
a = input("filename>>:")
# 输入文件名时不要带.py后缀
shell = f"cython {a}.py -3 --embed"
os.system(shell)
with open(a+'.c', 'r') as f:
content = f.read()
content = content.replace('wmain', 'main')
with open(a+'.c', 'w') as f:
content = f.write(content)
shell = f"x86_64-w64-mingw32-gcc-8.1.0 -mconsole -DSIZEOF_VOID_P=8 -DMS_WIN64 {a}.c -I D:/Python/include -L D:/Python/libs -l python37 -o {a} && {a} && pause"
os.system(shell)
7 其它:
1,其它电脑上可能不能执行该文件
缺少python.dll, 添加即可
2,我为什么不用pyinstaller打包
性能太差了,