【问题标题】:How to set python source code encoding with swig如何使用 swig 设置 python 源代码编码
【发布时间】:2022-01-01 19:54:04
【问题描述】:

当我用 swig 包装一个库时

swig -python my_ext.i

这会生成一个my_ext.py 文件。

使用distutils.extension.Extension 创建我的扩展时,如何在第一行添加文件编码?

# -*- coding: utf-8

我试过了:

%pythonbegin %{
# -*- coding: utf-8
%}

但我的评论是附加在 swig 横幅之后。

【问题讨论】:

  • 为什么?这似乎毫无意义。
  • 您的 SWIG 输出是否包含没有编码声明的非 ASCII 字符?如果是这样,那是一个 SWIG 错误。 (等等,不,他们在 3.0 中更改了默认值 - UTF-8 不需要编码声明。)
  • 我使用文档字符串来生成文档。所以我的.i文件是utf-8,包含很多é、è、à、...而且我还需要维护py2代码。
  • 哦,你还在使用 Python 2 吗?这可以解释一些事情。

标签: python swig python-2.x


【解决方案1】:

我找到的唯一解决方案是覆盖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},
    ...
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2015-04-27
    • 2014-07-25
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多