python启动程序

本文介绍了如何将Python程序编译为exe文件,并通过使用Python27.dll中的Py_main函数来实现独立运行。具体步骤包括设置32位编译环境,用VS2013的cl和link工具进行编译和链接,确保生成的launch.exe能在Windows XP上运行。启动时,launch.exe需与python27.dll在同一目录下,并指定运行的Python脚本。

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放到根目录下就可以了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值