py.cpp:
#include <iostream> #include <boost/python.hpp> #include <Python.h> using namespace boost::python; using namespace std; int main() { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); object simple = exec_file("test.py",main_namespace, main_namespace); object fun= main_namespace["fun"]; int val = extract<int>(fun(20)); cout << "fun(20) = "<< val << endl; Py_Finalize(); return 0; }
test.py:
def fun(i = 10): return i*10
编译: g++ py.cpp -o py -I/usr/include/python2.4 -lpython2.4 -lboost_python -L/usr/local/lib
执行:fun(20) = 200
当脚本文件修改后,服务不需要重启,即可立即生效。