python import出错_当文件具有导入语句时,Python C api PyImport_importmodule失败

1586010002-jmsa.png

I tried to use the Python C api to call a function from python in C++, the test was successful.

But if I intend to import a module already importing other module, the Pymodule_findmodule will return Null even though it's there and created a compiled file. Here is my code

Py_Initialize();

PySys_SetPath("C:/Users/Mik/Documents/GitHub/youtube-dl");

PyObject * pythonFile = PyImport_ImportModule("test2");

Here is the python filed named test2.py at that directory with a file named test_dl.py and a class called TESTDL inside it

from test_dl import TESTDL

def someFunction(someInput):

return 12345

As soon as I added the import line my program doesnot recognize it as module anymore

Edit: turns out the test_dl has the first line as:

from __future__ import unicode_literals

That's the reason I got this ImportError: No module named future

Thanks!

解决方案

A function call to PySys_SetPath() completely overwrites the Python module path. The result is that your Python script test_dl cannot find Python system modules (in this case __future__) and throws an exception.

What you need to do is to append the directory of your module to the system path instead. To do that, first query the existing value of the system path, and then add your path to it:

PyObject *sys_path = PySys_GetObject("path");

PyList_Append(sys_path, PyString_FromString("C:/Users/Mik/Documents/GitHub/youtube-dl"));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值