我有一个要使用Cython编译的Python项目。运行安装脚本后,我尝试运行test.py
并收到以下错误:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from root.pm1 import subsubsub as method
File "C:\parent_path\root\pm1\__init__.py", line 1, in <module>
from .f0 import subsubsub
File "root\pm1\f0.py", line 1, in init root.pm1.f0
import root.pm0 as runner
File "<frozen importlib._bootstrap>", line 1006, in _handle_fromlist
TypeError: hasattr(): attribute name must be string
当我使用root\pm1\f1.py
的第二行而不是第一行时,测试脚本将按预期工作。
我对更改编译器指令中的language_level
并不满意,并且不确定问题出在哪里。我做错了什么吗?如果没有,我是否有办法编译代码,以便可以使用第一种导入而不是第二种导入?
也可以在以下位置找到以下代码:https://github.com/bpolinsky/example
项目结构:
setup.py
test.py
root
L __init__.py
L pm0
L __init__.py
L f0.py
L pm1
L __init__.py
L f0.py
root / __ init __。py
root / pm0 / __ init __。py
from .f0 import do_thing
all = [
do_thing,
]
root / pm0 / f0.py
def do_thing():
print("doing thing 0")
root / pm1 / __ init __。py
from .f0 import subsubsub
root / pm1 / f0.py
import root.pm0 as runner
#import root.pm0.f0 as runner # This one works!!
def subsubsub():
runner.do_thing()
setup.py
from distutils.core import setup
from distutils.extension import Extension
import os
import sys
from Cython.Build import cythonize
from Cython.Distutils import build_ext
from Cython.Compiler import Options
Options.emit_code_commments = False
Options.generate_cleanup_code = True
TOP_DIR = "root"
NAME = "root"
PACKAGES = [
"root",
]
INCLUDE = []
file_ending = ".py"
COMPILE_ARGS = ["-O3", "-Wall"]
LINK_ARGS = ["-g"]
def get_extensions(directory):
extensions = list()
for f in os.listdir(directory):
path = os.path.join(directory, f)
if os.path.isfile(path) and path.endswith(file_ending):
path_split = os.path.split(path)
ext_name = path_split[0].replace(os.path.sep, ".")
module_name = path_split[1][:-len(file_ending)]
if module_name != "__init__":
ext_name += "." + str(module_name)
extensions.append(
Extension(
ext_name,
[
path,
],
include_dirs=[
".",
],
extra_compile_args=COMPILE_ARGS,
extra_link_args=LINK_ARGS,
)
)
elif os.path.isdir(path):
extensions.extend(get_extensions(path))
return extensions
# Build Extension objects
extensions = get_extensions(TOP_DIR)
# Do setup
setup(
name=NAME,
packages=PACKAGES,
ext_modules=cythonize(
extensions,
compiler_directives={
"language_level": "3",
},
),
include_dirs=INCLUDE,
cmdclass={
"build_ext": build_ext,
},
)
test.py
from root.pm1 import subsubsub as method
method()
其他信息:
setup.py
的Visual C ++ 2015 x86 x64交叉构建工具命令提示符(在EDM Shell中)答案 0 :(得分:0)
问题在于__all__
是一个字符串列表,而不是函数列表。
如果使它看起来像这样:
__all__ = [
'do_thing',
]
应该工作正常。