Python代码在shell中运行良好,但在文件中调用时则不然



我在终端外壳上运行了以下代码:

>>> import Strat
>>> x=Strat.Try()
>>> x.do_something()
You can do anything here!!!(this is the output of do_something)

但是当在文件中调用时,同一个文件不起作用:

import Strat
class Strategy:
def gen_fibonacci(self,ind,n):
x=Strat.Try()
x.do_something()
l=[]
num = 3
t1 = 0 
t2 = 1
nextTerm = 0
i=1
if ind==1:
l.append(0)
l.append(1)
i=3
if ind==2:
l.append(1)
i=2
while i<n:
nextTerm=t1+t2
t1=t2
t2=nextTerm
if num>=ind:
i=i+1
l.append(nextTerm)
num=num+1
return l

该代码给出以下错误:

Traceback (most recent call last):
File "./python_plugins/strat1.py", line 8, in gen_fibonacci
x=Strat.Try()
AttributeError: module 'Strat' has no attribute 'Try'

注意:这里Strat是一个带有类的共享库(so文件(尝试使用成员函数do_something((

strat.so文件是的编译版本

namespace python = boost::python;
class Strat
{
public:
virtual std::vector<long long> gen_fibonacci(int in,int n)= 0;
};
struct Try
{
void do_something() 
{ 
std::cout<<"You can do anything here!!!"<<"n";
}
};
class PyStrat final
: public Strat
, public bp::wrapper<Strat>
{
std::vector<long long> gen_fibonacci(int in,int n) override
{
get_override("gen_fibonacci")();
}
};

BOOST_PYTHON_MODULE(Strat)
{
bp::class_<Try>("Try")
.def("do_something", &Try::do_something)
;
bp::class_<std::vector<long long> >("Long_vec")
.def(bp::vector_indexing_suite<std::vector<long> >())
;

bp::class_<PyStrat, boost::noncopyable>("Strat")
.def("gen_fibonacci", &Strat::gen_fibonacci)
;
}

使用的编译命令:

g++ -I /usr/include/python3.6 -fpic -c -o Strat.o strat_helper.cpp
g++ -o Strat.so -shared Strat.o -L/usr/lib/x86_64-linux-gnu -lboost_python3-py36 -lpython3.6m

我正在使用boost python。

我看到您正在尝试导入C++函数。我想让你了解一下使用Boost的框架并阅读下面的链接,这可能会帮助你解决你的问题,用C或C++扩展Python SWIG是另一个可能有助于SWIG 的链接

这也会很有帮助。从Python调用C/C++?

最新更新