2022-4-18 c++ 调用 Python程序,安装Python3.8.9 动态库.so

2022-4-18 c++ 调用 Python程序,安装Python3.8.9 动态库.so,第1张

参考:
ubuntu16安装python3.8 pip3 pytorclass="superseo">ch

Ubuntu安装python3.7.5(附加更新python默认指向为python3.7)

  1. 下载源码压缩包
    https://www.python.org/ftp/python/
    解压,进入文件夹
  2. 安装
./configure --prefix=/usr/python --enable-shared CFLAGS=-fPIC

–prefix 选择安装Python头文件和库文件到的目录, --enable-shared CFLAGS=-fPIC 安装动态库,否则默认安装的是静态库,在动态调用时会报错undefined reference to 头文件里的函数。

  1. make
    sudo make
    sudo make test (参考教程2说不 make test 会报错,未遇到)
    (更新:Python安装过程没报错,之后运行工程报错了,no module named _ctypes ,按照教程2的参考修改后正常了)

  2. make install
    sudo make install

  3. 配置路径等

添加环境变量

PATH=$PATH:$HOME/bin:/usr/local/python3.8.9/bin

查看环境变量
echo $PATH

6. 更新python默认指向为python3.8

ls -l /usr/bin | grep python

参考:需修改

mv /usr/bin/python /usr/bin/python.bak
ln -s /usr/local/python3.7.5/bin/python3.7 /usr/bin/python
mv /usr/bin/pip /usr/bin/pip.bak
ln -s /usr/local/python3.7.5/bin/pip3 /usr/bin/pip

输入Python验证
python: error while loading shared libraries: libpython3.8.so.1.0: cannot open shared object file: No such file or directory

Python.so 未加入动态库配置路径中。参考之前的文章修改

sudo gedit /etc/ld.so.conf

添加python.3.8.9.so 所在目录
/usr/local/python3.8.9/

已添加?更新配置

sudo /sbin/ldconfig -v

再次Python:

测试c++ 执行Python文件:
pyprint.py:

def say():
	print("this is a simple python function test in c++ ")


if __name__ == '__main__':
	print("main function : ") 
	say()

c++ (qt5.4,ubuntu18 )

main.cpp

#include 
//#include 
#include 
#include 


using namespace std;
//using namespace boost::python;


PyObject* pyModule = NULL;
PyObject* pyFunc = NULL;
PyObject* pname = NULL;


int main()
{
    cout << "Hello World!" << endl;
    Py_Initialize();
    if(Py_IsInitialized())
    {
        cout << "c++ - python initialized " << endl;
    }
    else
    {
        cout << "c++ - python initialize failed " << endl;
    }


    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('../pythonscript/')");

    pyModule = PyImport_ImportModule("pyprint");

    pyFunc = PyObject_GetAttrString(pyModule, "say");

    if( pyModule == NULL )
    {
        cout <<"module not found" << endl;
    }

    if( !pyFunc || !PyCallable_Check(pyFunc)){
        cout <<"not found function add_num" << endl;
    }

    PyObject_CallObject(pyFunc, NULL);



    Py_Finalize();


    return 0;
}

pythontest.pro

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
        main.cpp

INCLUDEPATH +=\
    /usr/local/python3.8.9/include\
    /usr/local/python3.8.9/include/python3.8

LIBS +=\
    -L/usr/local/python3.8.9/lib/ -lpython3.8

编译执行:

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/715307.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-25
下一篇2022-04-25

发表评论

登录后才能评论

评论列表(0条)

    保存