python程序可以使用py2exe编译成exe文件来执行,从网上发现有这样一个独立运行的方法:
http://arctrix.com/nas/python/standalone.html
原理很简单,使用python27.dll中的Py_main函数来启动脚本,源代码也很简单,只有10来行c程序,于是自己编译成了2.7版的,还是遇到了点小麻烦,记下来。
# -*- coding: utf-8 -*-
from Tkinter import *
def main():
root = Tk()
root.title(u'Hello World!')
Label(root, text=u'Hello World').pack(padx=40, pady=40)
root.mainloop()
if __name__ == '__main__':
main()
#include <windows.h>
typedef int (__cdecl *PYMAIN)(int, char **);
static HINSTANCE dll = NULL;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow )
{
int rc;
char *args[3];
// junk on the end of strings so the binary can be hacked
args[0] = "app/main.py\000ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
args[1] = "app/main.py\000ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
args[2] = lpCmdLine;
HINSTANCE dll = LoadLibrary("python27.dll");
PYMAIN Py_Main = (PYMAIN) GetProcAddress(dll, "Py_Main");
rc = (Py_Main)(3, args);
return rc;
}
// console version
#include <windows.h>
typedef int (__cdecl *PYMAIN)(int, char **);
static HINSTANCE dll = NULL;
int main(int argc, char **argv)
{
int rc;
char *args[3];
// junk on the end of strings so the binary can be hacked
args[0] = "app/launch.py\000ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
args[1] = "app/launch.py\000ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
HINSTANCE dll = LoadLibrary("python25.dll");
PYMAIN Py_Main = (PYMAIN) GetProcAddress(dll, "Py_Main");
if (argc > 1) {
args[2] = argv[1];
rc = (Py_Main)(3, args);
} else {
rc = (Py_Main)(2, args);
}
return rc;
}
vs2013下
打开命令提示符
运行:设置32位编译环境
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\vcvars32.bat
编译程序:
cl launch.cpp
生成:launch.exe 和launch.obj
此时的launch.exe 不能在xp下运行,因为vs2012以后默认编译需要的操作系统版本较高,估计是vista,因此,需要自己链接程序
link /subsystem:windows,5.01 launch.obj
这样生成的launch.exe 就可以在windowsxp下运行了
使用方法:
launch.exe 指定 运行app目录下的main.py,因此只要指定好启动文件就可以了
python27.dll要和launch.exe在同一目录下
具体的目录结构直接复制python的安装目录就可以了,最小需要包括:
DLLs
Lib
tcl
launch.exe
python27.dll
没有在python3下测试,python3.5有嵌入版,估计更应该没问题,直接把这个exe放到根目录下就可以了
本文介绍了如何将Python程序编译为exe文件,并通过使用Python27.dll中的Py_main函数来实现独立运行。具体步骤包括设置32位编译环境,用VS2013的cl和link工具进行编译和链接,确保生成的launch.exe能在Windows XP上运行。启动时,launch.exe需与python27.dll在同一目录下,并指定运行的Python脚本。
6624

被折叠的 条评论
为什么被折叠?



