无法从linux,c ++执行“ my_script” python脚本的“ main(filename)”功能; pModule = PyImport_Import(pName);返回null

时间:2019-07-19 01:16:26

标签: python c++ linux python-embedding

试图从Linux,c ++的main(filename)调用my_script.py的{​​{1}}函数。

对于main(),pName不为NULL,但下一次调用pName = PyUnicode_DecodeFSDefault(argv[1]); pModule为NULL。

my_script的主要功能将使用图像的文件名作为参数,并返回一个包含菜名的字符串。这里pModule = PyImport_Import(pName); pModule返回null。

我尝试pModule = PyImport_Import(pName);得到了pwd

/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognitionexport PYTHONPATH=/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition仍然为NULL

pModule
int main(int argc, char* argv[])
{

    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue, *syspath;
    int i;
    char * str = get_current_dir_name();
    char* path, *eximpath = "/etc/exim";
    cout<<"str="<<str<<endl;
    if (argc < 3) {
        fprintf(stderr,"Usage: call pythonfile funcname [args]\n");
        return 1;
    }
    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }

    Py_SetProgramName(program);
    Py_Initialize();


    system("echo $PYTHONPATH");
    pName = PyUnicode_DecodeFSDefault(argv[1]);
    /* Error checking of pName left out */

    if(pName)
       cout<<"OK:"<<endl;

    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if(pModule) cout<<"success"<<endl;

     if (pModule != NULL)
  {
             cout<<"success"<<endl;
         pFunc = PyObject_GetAttrString(pModule, argv[2]);
         /* pFunc is a new reference */

         if (pFunc && PyCallable_Check(pFunc))
         {
             pArgs = PyTuple_New(argc - 3);
             for (i = 0; i < argc - 3; ++i)
             {
                 pValue = PyLong_FromLong(atoi(argv[i + 3]));
                 if (!pValue)
                 {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                 }
                 /* pValue reference stolen here: */
                 PyTuple_SetItem(pArgs, i, pValue);
             }
             pValue = PyObject_CallObject(pFunc, pArgs);
             cout<<"success"<<endl;
             Py_DECREF(pArgs);
             if (pValue != NULL)
             {
                 printf("Result of call: %ld\n", PyLong_AsLong(pValue));
                 Py_DECREF(pValue);
             }
             else
             {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
return 1;
             }

         }
         else
         {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
         }
         Py_XDECREF(pFunc);
         Py_DECREF(pModule);

     }
     else
     {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    if (Py_FinalizeEx() < 0)
    {
        return 120;
    }
}

我正在使用的运行代码 ./pyembed my_script主要download.jpeg

我从头开始编写了一个新函数和2个脚本文件。两个脚本文件的内容相同。但是它在1中运行,而在其他中却给出错误。 an.py->

output-
str=/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition
/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition
OK:
  File "/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/my_script.py", line 135
    return ('unknown')
                     ^
TabError: inconsistent use of tabs and spaces in indentation
Failed to load "my_script"

myscript.py->

#!/usr/bin/python

def fun(name):
    return 4

embedpy.c的内容

#!/usr/bin/python

#import cv2
#import numpy as np

def fun(name):
   return 4

我正在和

一起跑步
int main(int argc, char* argv[])
{

    wchar_t* program;
    PyObject *pName, *pModule, *pFunc;
    PyObject *pArgs, *pValue, *syspath;
    int i;

    if(argc<3)
    {
        cerr<<"Usage: call pythonfile funcname [args]\n"<<endl;
        return 1;
    }

    program = Py_DecodeLocale(argv[0],NULL);

    Py_SetProgramName(program);
    Py_Initialize();


    pName = PyUnicode_DecodeFSDefault(argv[1]);

    if(!pName)
    {
        cerr<<"error in pName"<<endl;

        return 1;
    }


    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if(!pModule)
    {
        PyErr_Print();
        cerr<<"error in pModule"<<endl;

        return 1;
    }

    pFunc = PyObject_GetAttrString(pModule, argv[2]);

    if(!pFunc || !PyCallable_Check(pFunc))
    {
        if (PyErr_Occurred())
                PyErr_Print();
        cerr<<"can not find function"<<argv[2]<<endl;

        return 1;
    }

    pArgs = PyTuple_New(argc - 3);
    for(int i = 0; i < argc-3; i++)
    {
        pValue = PyLong_FromLong(atoi(argv[i + 3]));

        if(!pValue)
        {
            Py_DECREF(pArgs);
            Py_DECREF(pModule);

            cerr<<"can not convert argument"<<endl;

            return 1;
        }

        PyTuple_SetItem(pArgs, i, pValue);
    }


    }

    pValue = PyObject_CallObject(pFunc, pArgs);
    Py_DECREF(pArgs);

    if(!pValue)
    {
        Py_DECREF(pFunc);
        Py_DECREF(pModule);

        PyErr_Print();
        cerr<<"function call failed"<<endl;

        return 1;
    }

    cout<<"Result of Call = "<<PyLong_AsLong(pValue)<<endl;
    Py_DECREF(pValue);


    if (Py_FinalizeEx() < 0)
    {
        return 120;
    }

}

./embedpy an fun download.jpeg

在第一种情况下出现错误- ModuleNotFoundError:没有名为“ an”的模块 pModule错误

在第二种情况下没有错误 通话结果= 4

我真正的问题(实际)是我无法跑步

./embedpy myscript fun download.jpeg

错误- ModuleNotFoundError:没有名为“ my_script”的模块 pModule错误

./embedpy my_script main download.jpeg

我使用复制

ls -l gives
-rw-r--r-- 1 sandeep sandeep       47 Jul 19 14:31 an.py
-rwxrwxrwx 1 sandeep sandeep     3947 Jul 19 13:50 my_script.py
-rw-r--r-- 1 sandeep sandeep       79 Jul 19 14:31 myscript.py
-rwxr-xr-x 1 sandeep sandeep    13816 Jul 19 13:59 embedpy
-rw-r--r-- 1 sandeep sandeep     1804 Jul 19 13:54 embedpy.cpp
-rw-r--r-- 1 sandeep sandeep       79 Jul 19 14:53 script2.py

但是

cp myscript.py script2.py

ModuleNotFoundError:没有名为“ script2”的模块 pModule错误

./embedpy script2 fun download.jpeg 

通话结果= 4

奇怪-> 我做到了

./embedpy myscript fun download.jpeg

export PYTHONPATH=/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition

给予

通话结果= 4

./embedpy an fun download.jpeg
./embedpy myscript fun download.jpeg
./embedpy script2 fun download.jpeg

给予 文件“ /home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/my_script.py”,第136行     返回(“未知”)                      ^ TabError:缩进中的制表符和空格不一致使用

pModule中的错误

我正在尝试从“ my_script.py”到“ an.py”一一包含元素 我包括了2个导入,但它给出了错误

an.py->

./embedpy my_script main download.jpeg

给予 追溯(最近一次通话):   文件“ /home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/an.py”,第3行,在     导入cv2 ModuleNotFoundError:没有名为“ cv2”的模块 pModule错误

任何猜测-出了什么问题,python文件独立执行ok 我输入了控制台“ conda update anaconda-navigator” 康达:找不到命令

1 个答案:

答案 0 :(得分:0)

您编写的程序是C ++,如果您将文件扩展名添加为my_script.py,它将无法正常工作。尝试将文件扩展名更改为my_script.cpp。错误本身与制表符的缩进和使用有关,这在python中是必需的,而不是使用大括号。 并在程序中将软件包作为标题包含在内,供您使用。