当我用swig 包装库时
swig -python my_ext.i
这将生成一个my_ext.py
文件。
使用distutils.extension.Extension
创建扩展名时,如何在第一行添加文件编码?
# -*- coding: utf-8
我试过:
%pythonbegin %{
# -*- coding: utf-8
%}
但我的评论是附加在swig横幅之后。
我找到的唯一解决方案是覆盖build_ext
命令:
from setuptools.command.build_ext import build_ext as _build_ext
if sys.version_info[0] == 2:
class build_ext(_build_ext):
def swig_sources(self, sources, extension):
new_sources = _build_ext.swig_sources(self, sources, extension)
for src in sources:
py_src = os.path.splitext(src)[0].replace("-", "_") + ".py"
if os.path.exists(py_src):
with open(py_src) as infile:
content = infile.read()
with open(py_src, "w") as outfile:
outfile.write("# -*- coding: utf-8 -*-n")
outfile.write(content)
return new_sources
else:
build_ext = _build_ext
...
setup(
cmdclass={"build_ext": build_ext},
...
)