【问题标题】:Running program on computers without python在没有python的计算机上运行程序
【发布时间】:2017-04-03 21:04:47
【问题描述】:

我已经编写了基于 c++ 的游戏,它使用 python 脚本来计算对象属性并绘制它们。但主要问题是它不会在没有安装 python2.7 的电脑上运行。我没主意了。我应该怎么做,让它在没有 python 的电脑上运行?

【问题讨论】:

  • 你想在没有 Python 的情况下运行 Python?
  • 一种可能的解决方案是让Cython 将 Python 函数编译为 DLL/共享库,并将它们包含在您的代码中并生成。

标签: python c++ python-2.7


【解决方案1】:

Python 有一个很棒的 C 语言 API。您可以使用它来运行您的脚本。 例如,此代码将从 python 模块运行一个函数:

#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc, *pValue;

    if (argc < 3) 
    {
        printf("Usage: exe_name python_source function_name\n");
        return 1;
    }

    // Initialize the Python Interpreter
    Py_Initialize();

    // Build the name object
    pName = PyString_FromString(argv[1]);

    // Load the module object
    pModule = PyImport_Import(pName);

    // pDict is a borrowed reference 
    pDict = PyModule_GetDict(pModule);

    // pFunc is also a borrowed reference 
    pFunc = PyDict_GetItemString(pDict, argv[2]);

    if (PyCallable_Check(pFunc)) 
    {
        PyObject_CallObject(pFunc, NULL);
    } else 
    {
        PyErr_Print();
    }

    // Clean up
    Py_DECREF(pModule);
    Py_DECREF(pName);

    // Finish the Python Interpreter
    Py_Finalize();

    return 0;
}

有关更多详细信息,请参阅Extending Python with C or C++。在 cpython 源代码的Demo/embed 目录中查看更多示例。

确保使用 python 库静态编译代码。否则,它仍然需要安装的 python 版本。

但是,请记住,您只有一个 python 解释器,而不是完整的 python 安装。因此,如果不将它们放在本地,您将无法使用几乎任何 python 模块。

【讨论】:

  • 安装了python的代码可以正常运行,但我需要让它在没有安装python的情况下在pc上运行。
  • @SergeBallesta,是的,请参阅此处了解更多信息:github.com/python/cpython/tree/2.7/Demo/embed。确保静态编译它。
  • 静态链接是您的答案中缺少的内容。但无论如何,它只适用于核心或本机功能。但是一旦你从标准库中导入一个纯 Python 模块,你就会松懈:如果你没有安装 Python,你在哪里可以找到 Python(源)模块?
  • @SergeBallesta 我已经更新了答案。您对标准库是正确的,但是,您仍然可以使用您的程序复制所需的模块。对于具有很多依赖项的 python 脚本,我不建议这样做。在这种情况下,将模块移植到 C 可能更容易。
  • 添加标准库中模块的限制,我会投票。
【解决方案2】:

制作一个游戏安装程序,它将安装所有必需的依赖项。

【讨论】:

    【解决方案3】:

    关注本教程:http://www.py2exe.org/index.cgi/Tutorial

    您可能需要进行一些调整,但您可以使用 py2exe 将您的 python 脚本转换为 exe 和 dll。

    也许您可以尝试使用以下命令将您的 python 转换为 C:http://cython.org/ 然后在你的 C++ 程序中用 extern "C" 引用它:

    extern "C"{
         //C Code Here
    };
    

    可能会引用 py2exe 输出的 dll 中的导出函数。

    希望这可能会有所帮助。

    祝你好运!

    【讨论】:

    • 他想将python程序嵌入到C++程序中。不要在没有本地 python 解释器的情况下运行 python。
    • 在这种情况下,您可以在 dll 中使用导出的函数并在 c++ 中调用它们。
    猜你喜欢
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多