在C ++中嵌入python:无法识别python脚本 [英] embedding python in c++: python script not recognized

查看:119
本文介绍了在C ++中嵌入python:无法识别python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将python脚本嵌入到c ++项目中。
以下是到目前为止我尝试过的内容。

I am trying to embed python script into c++ project. Below is what I have tried so far.

#include<iostream>
#include <Python.h>

int
main()
{
    Py_Initialize();
    PyObject* sysPath = PySys_GetObject("path"); 
    PyObject* modPath = PyBytes_FromString("C:\\Users\\naal\\Documents\\Visual Studio 2017\\Projects\\Project1\pyscripts");
    int result = PyList_Insert(sysPath,0, modPath);
    PyObject *pModule = PyImport_ImportModule("myscript2");
    printf("%p\n", pModule);
    return 0;
}

下面是python脚本 myscript2.py

below is the python script "myscript2.py"

def find_me():
    print("hey you found me")

问题是,无论我如何更改python脚本路径,主模块都无法找到python脚本,即对象pyModule始终为NULL。

The problem is, the main module is not able to find the python script i.e object pyModule is always NULL, no matter how I change python script path.

我在做什么错了?

推荐答案

我最终实现了这是另一种方式。

I ended up implementing this in another way.

#include<iostream>
#include <Python.h>

int main() {    
       std::string location = "C:\\Users\\myscript.py";     
       const char* file_location = location.c_str();    FILE* file_pointer;          
       Py_Initialize();
       file_pointer = _Py_fopen(file_location, "r");
       PyRun_SimpleFile(file_pointer, file_location);

       Py_Finalize();
       return 1;
       }

以上似乎有效。我仍然不知道为什么最初在问题中提到的SYSPATH想法不起作用。

The above seemed to work. I still don't know why the SYSPATH idea originially mentioned in the question didn't work.

这篇关于在C ++中嵌入python:无法识别python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆