python - 如何从 cython 安装文件中删除 -pthread 编译器标志

标签 python cython compiler-optimization cythonize

在 linux 环境下,当我运行 cython 的安装脚本时,我得到了

gcc -pthread -B /apps/.../compiler_compat -Wl,-sysroot=/ -Wsign-compare 
-DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/ap......  

对于我的情况,我想删除 pthread 选项。我如何通过 cython 安装文件做到这一点?我看到有添加编译器标志的选项,但没有要删除的选项。我的设置文件:

from distutils.core import setup
from Cython.Build import cythonize

from distutils.extension import Extension

extensions = [Extension("foo",sources = ["foo.pyx"])]                                 

setup(ext_modules = cythonize(extensions))

最佳答案

正如@DavidW 指出的那样,对于许多选项,还有一个选项可以否定/覆盖它,命令行上的最后一个选项“获胜”。因此,例如添加额外的编译选项 -Os 将否决默认设置 -O2-O3,因为 -Os 将出现在命令行上的 -O2 之后(-fwrapv/-fno-wrapv 此类对的另一个示例)。

但是,-pthread 没有这样的“伙伴”,禁用它的唯一机会就是完全阻止它出现在命令行中。实现它的方法有些 hacky,但这种 hackiness 不是我们都使用 python 的原因吗?

distutils 使用 distutils.sysconfig 找到正确的编译/链接标志。一种可能性是修改其功能,以便过滤掉 -pthread

我选择get_config_vars ,但当然还有其他选择。计划很简单:

  1. 包装distutils.sysconfig.get_config_vars,以便过滤掉-pthread
  2. 用包装器替换 distutils.sysconfig.get_config_vars
  3. 否则,setup.py不变

这导致以下 setup.py:

# manipulate get_config_vars:
# 1. step: wrap functionality and filter
from distutils.sysconfig import get_config_vars as default_get_config_vars

def remove_pthread(x):
    if type(x) is str:
        # x.replace(" -pthread ") would be probably enough...
        # but we want to make sure we make it right for every input
        if x=="-pthread":
            return ""
        if x.startswith("-pthread "):
            return remove_pthread(x[len("-pthread "):])
        if x.endswith(" -pthread"):
            return remove_pthread(x[:-len(" -pthread")])
        return x.replace(" -pthread ", " ")
    return x

def my_get_config_vars(*args):
  result = default_get_config_vars(*args)
  # sometimes result is a list and sometimes a dict:
  if type(result) is list:
     return [remove_pthread(x) for x in result]
  elif type(result) is dict:
     return {k : remove_pthread(x) for k,x in result.items()}
  else:
     raise Exception("cannot handle type"+type(result))

# 2.step: replace    
import distutils.sysconfig as dsc
dsc.get_config_vars = my_get_config_vars


# 3.step: normal setup.py

from distutils.core import setup
from Cython.Build import cythonize

from distutils.extension import Extension

extensions = [Extension("foo",sources = ["foo.pyx"])]                                 

setup(ext_modules = cythonize(extensions))

我不完全确定,在没有 -pthread 的情况下构建并将生成的模块加载到使用 -pthread 构建的 python 解释器中是个好主意> - 不确定它是否会以某些微妙的方式中断并按预期工作。

关于python - 如何从 cython 安装文件中删除 -pthread 编译器标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57046796/

相关文章:

python - 如何从自定义 COCO 数据集中保存图像,并将其注释叠加在其上

python - 列表理解中的多个打印功能

python - 删除不存在的记录应该在 sqlalchemy 中引发错误

python - Cython编译错误

c - C中的浮点运算是关联的吗?

python - 如何将numpy数组转换为libsvm格式

python - 从 Numba jitted 代码调用 Cython 函数

python - 我应该将我的 cython 文件放在 python 发行版中的什么位置?

c - GCC 为数组元素的重复 XOR 生成冗余代码

gcc - 从静态可执行文件中剥离未使用的库函数/死代码