C - 导入 Python 模块

C - Importing Python Module

我正在使用 <Python.h> 库,这是我第一次使用它,我做了一些研究。最后我发现我的问题到底是什么,但真的不知道如何解决它。

我想用 Beautifulsoup 解析 url,Python 代码工作得很好,但是当我想使用 PyImport_ImportModule(parser) 导入我的文件(名为 parser.py) 但它无法识别我导入的 bs4 模块 from bs4 import BeautifulSoup.

这是我的 C 程序的一部分:

    PyObject *return, *module, *function, *args;

    Py_Initialize();

    PySys_SetPath(".");
    module = PyImport_ImportModule("parser");

    if(module == NULL){
        PyErr_Print();
        exit(1);
    }
    fonction = PyObject_GetAttrString(module, "link_list");

其中 link_list 是我的 Python 函数,它只接受一个字符串。所以我知道我也必须使用 PyImport 导入 bs4 但没有任何工作正常而且我仍然有这个错误:

Traceback (most recent call last): File "./parser.py", line 2, in from bs4 import BeautifulSoup ImportError: No module named bs4

我坚持我的 parser.py 与 Python2.7 完美配合,当我编译我的 C 程序时我使用 gcc -I/usr/include/python2.7 pars.c -lpython2.7 -o pars -Wall 但是如果你需要看看我是如何使用它的我的 Python 程序:

#!/usr/local/bin/python3
from bs4 import BeautifulSoup
import urllib2


def link_list(urlString):
    siteFile = urllib2.urlopen(urlString)
    siteHTML = siteFile.read()
    siteFile.close()
    soup = BeautifulSoup(siteHTML, "html.parser")
    liste = []
    for links in soup.find_all('a'):
        print(links.get('href'))
        liste.append(links.get('href'))
    return liste

更新:已修复!

如果您在尝试导入任何模块(在我的例子中是 urllib2)时遇到问题,并且您会看到此错误:Symbol not found: __PyCodecInfo_GetIncrementalDecoder这意味着您肯定是 mac 用自制软件安装 Python 的用户。就我而言,我这样做了:

cp /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so /usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so

这取决于您使用的 Python 版本。如果您没有此功能,请使用 sudo find / -name _io.so 并查找 _io.so 的 /System 路径和具有最新版本 python 的 /usr/local/Cellar/python/ 并使用cp与他们一起指挥。

这对我有用,请试试这个:

    /* 1st: Import the module */
    PyObject* ModuleString = PyString_FromString((char*) "parser");
    if (!ModuleString) {
        PyErr_Print();
        printf("Error formating python script\n");
    }

    PyObject* Module = PyImport_Import(ModuleString);
    if (!Module) {
        PyErr_Print();
        printf("Error importing python script\n");
    }

    /* 2nd: Getting reference to the function */
    PyObject* Function = PyObject_GetAttrString(Module, (char*)"link_list");
    if (!Function) {
        PyErr_Print();
        printf("Error getting link_list()\n");
    }

更新:

附上完整过程,在MacOS上编译。

[milinddeore@MDEORE-M-P028: ~/temp ] ls
__init__.py pars.c      parser.py
[milinddeore@MDEORE-M-P028: ~/temp ] vim pars.c

#include <stdio.h>
#include <Python.h>

int main() {
  Py_Initialize();

  /* This is to add the path in the code */
  PyObject *sys = PyImport_ImportModule("sys");
  PyObject *path = PyObject_GetAttrString(sys, "path");
  PyList_Append(path, PyString_FromString("."));

  /* 1st: Import the module */
    PyObject* ModuleString = PyString_FromString((char*) "parser");
    if (!ModuleString) {
        PyErr_Print();
        printf("Error formating python script\n");
    }

    PyObject* Module = PyImport_Import(ModuleString);
    if (!Module) {
        PyErr_Print();
        printf("Error importing python script\n");
    }

    /* 2nd: Getting reference to the function */
    PyObject* Function = PyObject_GetAttrString(Module, (char*)"link_list");
    if (!Function) {
        PyErr_Print();
        printf("Pass valid argument to link_list()\n");
    }

    Py_Finalize();
    return 0;
}
[milinddeore@MDEORE-M-P028: ~/temp ] vim parser.py
#!/usr/local/bin/python2.7
from bs4 import BeautifulSoup
import urllib2


def link_list(urlString):
    siteFile = urllib2.urlopen(urlString)
    siteHTML = siteFile.read()
    siteFile.close()
    soup = BeautifulSoup(siteHTML, "html.parser")
    liste = []
    for links in soup.find_all('a'):
        print(links.get('href'))
        liste.append(links.get('href'))
    return liste
[milinddeore@MDEORE-M-P028: ~/temp ] gcc -I/usr/include/python2.7 pars.c -lpython2.7 -o pars -Wall
[milinddeore@MDEORE-M-P028: ~/temp ] ls
__init__.py pars        pars.c      parser.py
[milinddeore@MDEORE-M-P028: ~/temp ] ./pars
AttributeError: 'module' object has no attribute 'link_list'
Pass valid argument to link_list()     ===> This is because i have not passed the required argument to the function. 

如果您需要任何其他详细信息,请告诉我。希望这有帮助。