简体   繁体   English

从另一个目录导入Cython公开的类

[英]Import Cython exposed class from another directory

I have a Python project in which I want to make use of a C++ class that I exposed through Cython (really, I just need a specific instance of the class, as the code below will demonstrate). 我有一个Python项目,我想在其中使用通过Cython公开的C++类(确实,我只需要该类的特定实例,如下面的代码所示)。 Because there were a bunch of files associated with the class I decided to put it in its own package. 因为有一堆文件与该类相关联,所以我决定将其放在自己的程序包中。

In the __init__.py file of this package, I have what amounts to the following code: 在此程序包的__init__.py文件中,我具有相当于以下代码的内容:

from foo import Foo  # import the class

bar = Foo(some_parameters)
__all__ = ["bar"]

This works fine when I run __init__.py by itself. 当我自己运行__init__.py时,此方法工作正常。 However, when I try to access it from outside the directory: 但是,当我尝试从目录外部访问它时:

from qux import bar  # inside main.py in the parent directory

I get the error traced back to the same __init__.py : 我得到的错误可以追溯到相同的 __init__.py

File "D:\path\to\qux\\__init__.py", line 2, in <module>
from foo import Foo
ImportError: No module named 'foo'

Recall that foo is a Cython file, not pure Python code. 回想一下foo是Cython文件,而不是纯Python代码。

The directory structure looks like this: 目录结构如下所示:

main_project\
  main.py
  (more supporting files here)
  qux\
    __init__.py
    cy_foo.cpp
    cy_foo.pyx
    foo.cpp
    foo.h
    foo.cp35-win_amd64.pyd
    (more supporting files here)

What's going on? 这是怎么回事?

I don't think this has anything to do with Cython per se, rather, this issue is due to the fact that when you execute main.py in the top level directory, Python will execute __init__.py and search in the same directory failing to locate the foo module inside qux . 我认为这与Cython本身Cython ,而是因为以下事实:当您在顶级目录中执行main.py时, Python将执行__init__.py并在同一目录中搜索失败在qux找到foo模块。

As a solution, change the import statement in __init__.py to: 作为解决方案,将__init__.pyimport语句更改为:

from qux.foo import Foo

If for some reason you still need to run __init__.py as the __main__ script, you can use the oh so familiar if clause to check the __name__ : 如果由于某些原因您仍然需要运行__init__.py作为__main__脚本,则可以使用非常熟悉的if子句来检查__name__

if __name__ == "__main__":
    from foo import Foo
else:
    from qux.foo import Foo

bar = Foo("arguments")
__all__ = ["bar"]

Now, if run as the __main__ module, __init__.py will find foo , if not, it allows others to find it. 现在,如果以__main__模块运行,则__init__.py将找到foo ,如果没有,它将允许其他人找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM