简体   繁体   中英

ImportError: cannot import name 'etree' in Visual Studio Debug console while running python file from C++

Using Embedded python with c++, I was able to call python file from C++.

Python file contains: from lxml import etree The python file runs successfully in python3.6 IDLE.

But while running the C++ in Visual studio debugging, finding the below error in VS debug console ImportError: cannot import name 'etree'.

How to resolve this error. Env details:

  1. VS 2019
  2. Python 3.6 (x86)
  3. lxml 4.6.2

Thanks in advance CPP code

#define PY_SSIZE_T_CLEAN
#include <iostream>
#include <Python.h>
#include <string>

int main()
{
    PyObject* pName{}, * pModule{}, * pDict{}, * pFunc{}, * pValue{}, * presult{};

    int data = 255;
    // Initialize the Python Interpreter
    Py_Initialize();
    // Build the name object
    pName = PyUnicode_FromString((char*)"Test_lxml");

        pModule = PyImport_Import(pName);
    if (pModule != NULL)
    {
        data = 254;
        std::cout << "Module != NULL\n";
        pDict = PyModule_GetDict(pModule);
        pFunc = PyDict_GetItemString(pDict, (char*)"verify_lxml");
        if (PyCallable_Check(pFunc))
        {
            pValue = Py_BuildValue("(z)", (char*)"1");
            PyErr_Print();
            presult = PyObject_CallObject(pFunc, pValue);
            PyErr_Print();
        }
        else
        {
            PyErr_Print();
        }
        data = 253;
        std::string val("");
        if (presult != NULL)
        {
            presult = PyUnicode_AsUTF8String(presult);
            val = std::string(PyBytes_AsString(presult));
            data = stoi(val);

            Py_DECREF(pValue);

            // Clean up
            Py_DECREF(pModule);
            Py_DECREF(pName);
            // Finish the Python Interpreter
            Py_Finalize();
        }
    }
    std::cout << "Module end\n";
    std::cout << data;
}

**Test_lxml.py**
      
def verify_lxml(expected_string):
        import sys
        sys.path.insert(1,r'C:\Program Files (x86)\Python36\Lib\site-packages')
        from lxml import etree
        print(expected_string)
        return expected_string
        
def main(): 

        verify_lxml('3')        
        
if __name__ == "__main__": 

        # calling main function
        main()

**Visual Studio Debug Console**
Module != NULL
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36\Lib\Test_lxml.py", line 6, in verify_lxml
    from lxml import etree
ImportError: cannot import name 'etree'
Module end
253

Visual Studio Configuration must be in Release instead of Debug. Thanks for the support

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM