c调用python脚本 载入脚本失败,在C ++中嵌入python:无法识别python脚本

I am trying to embed python script into c++ project.

Below is what I have tried so far.

#include

#include

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;

}

below is the python script "myscript2.py"

def find_me():

print("hey you found me")

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.

What am I doing wrong ?

解决方案

I ended up implementing this in another way.

#include

#include

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;

}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值