Skip to content
Advertisement

Reliable way to get the “build” directory from within setup.py

Inside the setup.py script I need to create some temporary files for the installation. The natural place to put them would be the “build/” directory.

Is there a way to retrieve its path that works if installing via pypi, from source, easy_install, pip, …?

Thanks a lot!

Advertisement

Answer

By default distutils create build/ in current working dir, but it can be changed by argument --build-base. Seems like distutils parses it when executing setup and parsed argument does not accessible from outside, but you can cut it yourself:

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 = "."

This naive version of parser still shorter than optparse‘s version with proper error handling for unknown flags. Also you can use argparse‘s parser, which have try_parse method.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement