将Python代码编译为exe文件,只调用所需的DLL

时间:2016-06-17 18:29:22

标签: python c++ numpy exe cython

关于这个主题似乎没有什么信息 - 我试过py2exe无济于事(Python 3.5错误),以及pyinstaller.后者似乎包括每一个扩展模块安装在系统上,除非它们在构建期间被特别排除,即使是小型构建也会被排除在50以上。我还看到了pyinstcxFreeze,您可以在其中指定要包含的包,并将Python与它捆绑在一起,但我想要简单和小巧。我所做的所有工作都涉及AT NumPySciPyPandas。通常这些都可以减少到NumPy只有函数,而我在Cython中重写的大多数复杂函数(memoryviews)。环顾互联网我发现python.exe是一个只调用Python.h并加载python35.dll的C ++程序 - 这表明这个C ++代码示例允许一个访问所有Python和NumPy功能如下:

#include "Python.h"
#include <\numpy\core\include\numpy\ required includes>

int
wmain(int argc, wchar_t **argv)
{
    wchar_t *myargs[3] = { argv[0], L"-m", L"myscript.py" };
    return Py_Main(3, myargs);
}

示例来自: https://blogs.msdn.microsoft.com/pythonengineering/2016/04/26/cpython-embeddable-zip-file/

有没有人有一个好方法或一个很好的参考来生成一个小型构建,其中只包含运行exe所需的内容?或者可以确认以上实际上会有修改吗?非常感谢,我认为这个技能是一个利基主题......

1 个答案:

答案 0 :(得分:0)

如果您可以使用相关性,则可以使用boost::python来提供帮助。

下面是一个完整的工作示例应用,它只链接boost_pythonpython2.7个共享库。 -O3版本只有51K。

导入python模块:

使用boost::python::exec执行import语句,将python模块导入boost::python::object

bp::object import(const std::string& module, const std::string& path)
{
    bp::object globals = bp::import("__main__").attr("__dict__");

    bp::dict locals;
    locals["module_name"] = module;
    locals["path"]        = path;

    // execute some python code which imports the file
    bp::exec("import imp\n"
             "new_module = imp.load_module(module_name, open(path), path, ('bp', 'U', imp.PY_SOURCE))\n",
             globals,
             locals);
    return locals["new_module"];
}

// get an object containing the contents of the file "test.py"
bp::object module = import("test", "test.py");

获取python模块中元素的句柄:

// get a handle to something declared inside "test.py"
bp::object Script = module.attr("Script");

实例化对象:

// Instantiate a script object
bp::object script = Script();

调用Script的成员函数:

// calls Script.run(), passing no arguments
script.attr("run")();

您还可以将C ++代码公开给python:

使用boost::python::class

将C ++类公开给刚刚导入的模块
struct Foo
{
    void func();
}

bp::object FooWrapper(
    bp::class_<Foo>("Foo")
        .def("func", &Foo::func)
    );

bp::object foo    = FooWrapper(); // instantiate a python wrapped Foo object
bp::object script = Script(foo);  // create a Script instance, passing foo 

工作示例:

test.py

class Script(object):
    def __init__(self, ifc):
        print 'created script'
        self.ifc = ifc

    def run(self):
        print 'running'
        self.ifc.execute(5)

    def result(self, i):
        print 'result={}'.format(i)

的main.cpp

#include <boost/python.hpp>

namespace bp = boost::python;

bp::object import(const std::string& module, const std::string& path)
{
    bp::object globals = bp::import("__main__").attr("__dict__");

    bp::dict locals;
    locals["module_name"] = module;
    locals["path"]        = path;

    bp::exec("import imp\n"
             "new_module = imp.load_module(module_name, open(path), path, ('bp', 'U', imp.PY_SOURCE))\n",
             globals,
             locals);
    return locals["new_module"];
}

///////////////////////////

class Runner
{
public:
    void init(bp::object script)
    {
        // capture methods at creation time so we don't have to look them up every time we call them
        _run    = script.attr("run");
        _result = script.attr("result");
    }

    void run()
    {
        _run(); // call the script's run method
    }

    void execute(int i) // this function is called by the python script
    {
        _result(i * 2); // call the script's result method
    }

    bp::object _run;
    bp::object _result;
};

int main()
{
    Py_Initialize();

    // load our python script and extract the Script class
    bp::object module = import("test", "test.py");
    bp::object Script = module.attr("Script");

    // wrap Runner and expose some functions to python
    bp::object RunnerWrapper(
        bp::class_<Runner>("Runner")
            .def("execute", &Runner::execute)
        );

    // create a python wrapped instance of Runner, which we will pass to the script so it can call back through it
    bp::object wrapper = RunnerWrapper();
    bp::object script  = Script(wrapper);

    // extract the runner instance from the python wrapped instance
    Runner& runner = bp::extract<Runner&>(wrapper);

    // initialise with the script, so we can get handles to the script's methods we require
    runner.init(script);

    runner.run();

    Py_Finalize();
    return 0;

<强>的CMakeLists.txt

cmake_minimum_required (VERSION 3.2.2)

find_package(Boost COMPONENTS python REQUIRED)
find_package(PythonLibs 2.7 REQUIRED)

add_executable            (py_embed main.cpp)
target_link_libraries     (py_embed ${Boost_PYTHON_LIBRARY} ${PYTHON_LIBRARIES})
target_include_directories(py_embed SYSTEM PRIVATE ${PYTHON_INCLUDE_DIRS})

可下载的源代码here