简体   繁体   English

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

[英]unable to execute “main(filename)” function of “my_script” python script from linux,c++; pModule = PyImport_Import(pName); returns null

trying to call main(filename) function of my_script.py from main() of Linux,c++. 试图从Linux,c ++的main()调用my_script.py main(filename)函数。

For pName = PyUnicode_DecodeFSDefault(argv[1]); 对于pName = PyUnicode_DecodeFSDefault(argv[1]); pName is not NULL, but next call pModule = PyImport_Import(pName); pName不为NULL,但下一次调用pModule = PyImport_Import(pName); pModule is NULL. pModule为NULL。

The main function of my_script will take filename of image as parameter and return a string containing the name of vegetable. my_script的主要功能将使用image的文件名作为参数,并返回包含菜名的字符串。 Here pModule = PyImport_Import(pName); 这里pModule = PyImport_Import(pName); pModule returns null. pModule返回null。

I tried pwd got /home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition 我尝试了pwd /home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition

export PYTHONPATH=/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition but still pModule is NULL export PYTHONPATH=/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognitionpModule仍然为NULL

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;
    }
}
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"

for running code I am using ./pyembed my_script main download.jpeg 我正在使用./pyembed my_script main download.jpeg运行代码

I wrote a new function and 2 script files from scratch. 我从头开始编写了一个新函数和2个脚本文件。 Contents of both the script files are same. 两个脚本文件的内容相同。 But it runs in 1 and gives error in other. 但是它在1中运行,而在其他位置却出错。 an.py-> an.py->

#!/usr/bin/python

def fun(name):
    return 4

myscript.py-> myscript.py->

#!/usr/bin/python

#import cv2
#import numpy as np

def fun(name):
   return 4

contents of embedpy.c embedpy.c的内容

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;
    }

}

I am running with 我一起跑步

./embedpy an fun download.jpeg

and

./embedpy myscript fun download.jpeg

in 1st case error - ModuleNotFoundError: No module named 'an' error in pModule 在第一种情况下发生错误-ModuleNotFoundError:pModule中没有名为“ an”的模块错误

in 2nd case no error Result of Call = 4 在第二种情况下,没有错误通话结果= 4

My real problem(practical) is I am unable to run 我真正的问题(实用)是我无法跑步

./embedpy my_script main download.jpeg

error- ModuleNotFoundError: No module named 'my_script' error in pModule 错误-ModuleNotFoundError:pModule中没有名为“ my_script”的模块错误

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

I copied using 我使用复制

cp myscript.py script2.py

but

./embedpy script2 fun download.jpeg 

ModuleNotFoundError: No module named 'script2' error in pModule ModuleNotFoundError:pModule中没有名为“ script2”的模块错误

and

./embedpy myscript fun download.jpeg

Result of Call = 4 通话结果= 4

Strange-> i did 奇怪->我做到了

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

and

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

give

Result of Call = 4 通话结果= 4

./embedpy my_script main download.jpeg

gives File "/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/my_script.py", line 136 return ('unknown') ^ TabError: inconsistent use of tabs and spaces in indentation 给出文件“ /home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/my_script.py”,行136返回(“未知”)^ TabError:缩进中的制表符和空格使用不一致

error in pModule pModule中的错误

I am trying to include elements 1 by 1 from "my_script.py" to "an.py" I included 2 imports and it gives error 我试图包括从“ my_script.py”到“ an.py”的元素1比1,我包含了2个导入,并且给出了错误

an.py-> an.py->

!/usr/bin/python

import cv2
import numpy as np

def fun(name):
    return 4

./embedpy an fun download.jpeg

gives Traceback (most recent call last): File "/home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/an.py", line 3, in import cv2 ModuleNotFoundError: No module named 'cv2' error in pModule 在导入cv2的第3行中提供文件“ /home/sandeep/Downloads/VegeTable-master/VegeTable/image_recognition/an.py”的行“回溯”(最近一次调用):ModuleNotFoundError:pModule中没有名为“ cv2”的模块错误

any guess- what is wrong, the python file executes ok independently I typed in console "conda update anaconda-navigator" conda: command not found 任何猜测-这是什么问题,我在控制台“ conda update anaconda-navigator” conda中键入的python文件独立执行ok:找不到命令

The program you have written is in C++ and if you add the file extension as my_script.py, it won't work. 您编写的程序是C ++,如果您将文件扩展名添加为my_script.py,它将无法正常工作。 Try changing the file extension to my_script.cpp. 尝试将文件扩展名更改为my_script.cpp。 The error itself is regarding the indentation and use of tabs, which is required in python instead of using curly brackets. 错误本身与制表符的缩进和使用有关,这在python中是必需的,而不是使用大括号。 And include the packages as headers in the program for you to use the packages. 并在程序中将程序包作为标题包含在内,以供您使用程序包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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