自己做網(wǎng)站軟件/2021拉新推廣傭金排行榜
實(shí)現(xiàn) Python UDF 中的一步就是學(xué)習(xí)如何在 C++ 語(yǔ)言中調(diào)用 python 解析器。本文根據(jù) Python 官方文檔做了一次實(shí)驗(yàn),記錄如下:
1. 安裝依賴包
$sudo yum install python3-devel.x86_64
2. 使用 python-config 來生成編譯選項(xiàng)
$python3.6-config --cflags --ldflags
-I/usr/include/python3.6m -I/usr/include/python3.6m -Wno-unused-result -Wsign-compare -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv-L/usr/lib64 -lpython3.6m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic
3. 編寫 Makefile
將第二步生成的編譯、鏈接選項(xiàng)填到 Makefile 中,得到 Makefile 如下:
all:g++ -I/usr/include/python3.6m -I/usr/include/python3.6m -Wno-unused-result -Wsign-compare -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -L/usr/lib64 -lpython3.6m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic main.cpp
4. 編寫 main.cpp
#define PY_SSIZE_T_CLEAN
#include <Python.h>int
main(int argc, char *argv[])
{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); /* optional but recommended */Py_Initialize();PyRun_SimpleString("from time import time,ctime\n""print('Today is', ctime(time()))\n");if (Py_FinalizeEx() < 0) {exit(120);}PyMem_RawFree(program);return 0;
}
5. 編譯
$make
g++ -I/usr/include/python3.6m -I/usr/include/python3.6m -Wno-unused-result -Wsign-compare -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -L/usr/lib64 -lpython3.6m -lpthread -ldl -lutil -lm -Xlinker -export-dynamic main.cpp
6. 執(zhí)行
$./a.out
Today is Wed Mar 1 14:23:13 2023
后繼章節(jié)預(yù)告
- 如何在腳本片段中使用第三方庫(kù)
- 如何傳參到 Python 腳本
- 如何處理 Python 腳本的返回值
- 并發(fā)調(diào)用 Python 解析器
- 效率討論
參考文獻(xiàn)
Embedding python in C++:https://docs.python.org/3/extending/embedding.html