将 SWIGged Python 库安装到 dist-packages/myfoo.py,而不是 dist-packages/myfoo/myfoo.py

Install SWIGged Python library into dist-packages/myfoo.py, not dist-packages/myfoo/myfoo.py

我的目录结构类似于

 setup.py
 myfoo/
     myfoo.i
     myfoo.cpp
     myfoo.hpp

setup.py

from distutils.core import setup, Extension

setup(
    name='myfoo',
    ext_modules=[
        Extension(
            '_myfoo',
            [
                'myfoo/myfoo.cpp',
                'myfoo/myfoo.i'
            ],
            swig_opts=['-c++'],
            )
        ],
    version='0.0.1',
    packages=['myfoo'],
    requires=[]
    )

myfoo.hpp

#ifndef MYFOO_HPP
#define MYFOO_HPP

int myfoo();

#endif  // MYFOO_HPP

myfoo.cpp

#include "myfoo.hpp"

#include <iostream>

int myfoo() {
  std::cout << "hey!" << std::endl;
  return 42;
}

当 运行 python setup.py install 时,包会正确构建并安装文件

/usr/local/lib/python2.7/dist-packages/
    _myfoo.so
    myfoo/
        myfoo.py
        myfoo.pyc

默认情况下,$PYTHONPATH 中只有 /usr/local/lib/python2.7/dist-packages/,因此来自任何地方的 import myfoo 都会产生导入错误。为此,myfoo.py[c] 都应在 /usr/local/lib/python2.7/dist-packages/ 中或重命名为 __init__.py。看来我没有正确调用setup.py

有什么提示吗?

删除

packages=['myfoo'],

并添加

py_modules = ['myfoo'],
package_dir = {'' : 'myfoo'}

setup.py 就可以了。