从setup.py中获取“build”目录的可靠方法

时间:2012-10-15 13:13:34

标签: python numpy setuptools distutils setup.py

在setup.py脚本中,我需要为安装创建一些临时文件。放置它们的自然地方是“build /”目录。

有没有办法检索通过pypi安装的路径,从source,easy_install,pip,...?

非常感谢!

2 个答案:

答案 0 :(得分:2)

默认情况下,distutils在当前工作目录中创建build/,但可以通过参数--build-base进行更改。似乎distutils在执行setup时解析它并且解析的参数无法从外部访问,但您可以自己剪切它:

import sys
build_base_long = [arg[12:].strip("= ") for arg in sys.argv if arg.startswith("--build-base")]
build_base_short = [arg[2:].strip(" ") for arg in sys.argv if arg.startswith("-b")]
build_base_arg = build_base_long or build_base_short
if build_base_arg:
    build_base = build_base_arg[0]
else:
    build_base = "."

这个天真的解析器版本仍然比optparse版本短,并且对未知标志进行了适当的错误处理。您也可以使用argparse的解析器,它具有try_parse方法。

答案 1 :(得分:0)

也许是这样的?在我的情况下使用 python 3.8

...
from distutils.command.build import get_platform
import sys
import os
...
def configuration(parent_package='', top_path=None):

    config = Configuration('', parent_package, top_path)
    # add xxx library
    config.add_library('xxx',['xxx/src/fil1.F90',
                            'xxx/src/file2.F90',
                            'xxx/src/file3.F90'],
                            language='f90')

    # check for the temporary build directory option
    _tempopt = None
    _chkopt = ('-t','--build-temp')
    for _opt in  _chkopt:
        if _opt in sys.argv:
            _i = sys.argv.index(_opt)
            if _i < len(sys.argv)-1:
                _tempopt = sys.argv[_i+1]
                break
    # check for the base directory option
    _buildopt = 'build'
    _chkopt = ('-b','--build-base')
    for _opt in  _chkopt:
        if _opt in sys.argv:
            _i = sys.argv.index(_opt)
            if _i < len(sys.argv)-1:
                _buildopt = sys.argv[_i+1]
                break    

    if _tempopt is None:
        # works with python3 (check distutils/command/build.py)
        platform_specifier = ".%s-%d.%d" % (get_platform(), *sys.version_info[:2])
        _tempopt = '%s%stemp%s'%(_buildopt,os.sep,platform_specifier)

    # add yyy module (wraps fortran code in xxx library)
    config.add_extension('fastpost',sources=['yyy/src/fastpost.f90'],
                          f2py_options=['--quiet'],
                          libraries=['xxx'])

    # to access the mod files produced from fortran modules comppilaton, add 
    # the temp build directory to the include directories of the configuration
    config.add_include_dirs(_tempopt)
    return config

setup(name="pysimpp",
      version="0.0.1",
      description="xxx",
      author="xxx",
      author_email="xxx@yyy",
      configuration=configuration,)