m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2438 lines
85 KiB

7 months ago
  1. import os
  2. import re
  3. import sys
  4. import copy
  5. import glob
  6. import atexit
  7. import tempfile
  8. import subprocess
  9. import shutil
  10. import multiprocessing
  11. import textwrap
  12. import importlib.util
  13. from threading import local as tlocal
  14. import distutils
  15. from distutils.errors import DistutilsError
  16. # stores temporary directory of each thread to only create one per thread
  17. _tdata = tlocal()
  18. # store all created temporary directories so they can be deleted on exit
  19. _tmpdirs = []
  20. def clean_up_temporary_directory():
  21. if _tmpdirs is not None:
  22. for d in _tmpdirs:
  23. try:
  24. shutil.rmtree(d)
  25. except OSError:
  26. pass
  27. atexit.register(clean_up_temporary_directory)
  28. __all__ = ['Configuration', 'get_numpy_include_dirs', 'default_config_dict',
  29. 'dict_append', 'appendpath', 'generate_config_py',
  30. 'get_cmd', 'allpath', 'get_mathlibs',
  31. 'terminal_has_colors', 'red_text', 'green_text', 'yellow_text',
  32. 'blue_text', 'cyan_text', 'cyg2win32', 'mingw32', 'all_strings',
  33. 'has_f_sources', 'has_cxx_sources', 'filter_sources',
  34. 'get_dependencies', 'is_local_src_dir', 'get_ext_source_files',
  35. 'get_script_files', 'get_lib_source_files', 'get_data_files',
  36. 'dot_join', 'get_frame', 'minrelpath', 'njoin',
  37. 'is_sequence', 'is_string', 'as_list', 'gpaths', 'get_language',
  38. 'quote_args', 'get_build_architecture', 'get_info', 'get_pkg_info',
  39. 'get_num_build_jobs', 'sanitize_cxx_flags',
  40. 'exec_mod_from_location']
  41. class InstallableLib:
  42. """
  43. Container to hold information on an installable library.
  44. Parameters
  45. ----------
  46. name : str
  47. Name of the installed library.
  48. build_info : dict
  49. Dictionary holding build information.
  50. target_dir : str
  51. Absolute path specifying where to install the library.
  52. See Also
  53. --------
  54. Configuration.add_installed_library
  55. Notes
  56. -----
  57. The three parameters are stored as attributes with the same names.
  58. """
  59. def __init__(self, name, build_info, target_dir):
  60. self.name = name
  61. self.build_info = build_info
  62. self.target_dir = target_dir
  63. def get_num_build_jobs():
  64. """
  65. Get number of parallel build jobs set by the --parallel command line
  66. argument of setup.py
  67. If the command did not receive a setting the environment variable
  68. NPY_NUM_BUILD_JOBS is checked. If that is unset, return the number of
  69. processors on the system, with a maximum of 8 (to prevent
  70. overloading the system if there a lot of CPUs).
  71. Returns
  72. -------
  73. out : int
  74. number of parallel jobs that can be run
  75. """
  76. from numpy.distutils.core import get_distribution
  77. try:
  78. cpu_count = len(os.sched_getaffinity(0))
  79. except AttributeError:
  80. cpu_count = multiprocessing.cpu_count()
  81. cpu_count = min(cpu_count, 8)
  82. envjobs = int(os.environ.get("NPY_NUM_BUILD_JOBS", cpu_count))
  83. dist = get_distribution()
  84. # may be None during configuration
  85. if dist is None:
  86. return envjobs
  87. # any of these three may have the job set, take the largest
  88. cmdattr = (getattr(dist.get_command_obj('build'), 'parallel', None),
  89. getattr(dist.get_command_obj('build_ext'), 'parallel', None),
  90. getattr(dist.get_command_obj('build_clib'), 'parallel', None))
  91. if all(x is None for x in cmdattr):
  92. return envjobs
  93. else:
  94. return max(x for x in cmdattr if x is not None)
  95. def quote_args(args):
  96. # don't used _nt_quote_args as it does not check if
  97. # args items already have quotes or not.
  98. args = list(args)
  99. for i in range(len(args)):
  100. a = args[i]
  101. if ' ' in a and a[0] not in '"\'':
  102. args[i] = '"%s"' % (a)
  103. return args
  104. def allpath(name):
  105. "Convert a /-separated pathname to one using the OS's path separator."
  106. splitted = name.split('/')
  107. return os.path.join(*splitted)
  108. def rel_path(path, parent_path):
  109. """Return path relative to parent_path."""
  110. # Use realpath to avoid issues with symlinked dirs (see gh-7707)
  111. pd = os.path.realpath(os.path.abspath(parent_path))
  112. apath = os.path.realpath(os.path.abspath(path))
  113. if len(apath) < len(pd):
  114. return path
  115. if apath == pd:
  116. return ''
  117. if pd == apath[:len(pd)]:
  118. assert apath[len(pd)] in [os.sep], repr((path, apath[len(pd)]))
  119. path = apath[len(pd)+1:]
  120. return path
  121. def get_path_from_frame(frame, parent_path=None):
  122. """Return path of the module given a frame object from the call stack.
  123. Returned path is relative to parent_path when given,
  124. otherwise it is absolute path.
  125. """
  126. # First, try to find if the file name is in the frame.
  127. try:
  128. caller_file = eval('__file__', frame.f_globals, frame.f_locals)
  129. d = os.path.dirname(os.path.abspath(caller_file))
  130. except NameError:
  131. # __file__ is not defined, so let's try __name__. We try this second
  132. # because setuptools spoofs __name__ to be '__main__' even though
  133. # sys.modules['__main__'] might be something else, like easy_install(1).
  134. caller_name = eval('__name__', frame.f_globals, frame.f_locals)
  135. __import__(caller_name)
  136. mod = sys.modules[caller_name]
  137. if hasattr(mod, '__file__'):
  138. d = os.path.dirname(os.path.abspath(mod.__file__))
  139. else:
  140. # we're probably running setup.py as execfile("setup.py")
  141. # (likely we're building an egg)
  142. d = os.path.abspath('.')
  143. if parent_path is not None:
  144. d = rel_path(d, parent_path)
  145. return d or '.'
  146. def njoin(*path):
  147. """Join two or more pathname components +
  148. - convert a /-separated pathname to one using the OS's path separator.
  149. - resolve `..` and `.` from path.
  150. Either passing n arguments as in njoin('a','b'), or a sequence
  151. of n names as in njoin(['a','b']) is handled, or a mixture of such arguments.
  152. """
  153. paths = []
  154. for p in path:
  155. if is_sequence(p):
  156. # njoin(['a', 'b'], 'c')
  157. paths.append(njoin(*p))
  158. else:
  159. assert is_string(p)
  160. paths.append(p)
  161. path = paths
  162. if not path:
  163. # njoin()
  164. joined = ''
  165. else:
  166. # njoin('a', 'b')
  167. joined = os.path.join(*path)
  168. if os.path.sep != '/':
  169. joined = joined.replace('/', os.path.sep)
  170. return minrelpath(joined)
  171. def get_mathlibs(path=None):
  172. """Return the MATHLIB line from numpyconfig.h
  173. """
  174. if path is not None:
  175. config_file = os.path.join(path, '_numpyconfig.h')
  176. else:
  177. # Look for the file in each of the numpy include directories.
  178. dirs = get_numpy_include_dirs()
  179. for path in dirs:
  180. fn = os.path.join(path, '_numpyconfig.h')
  181. if os.path.exists(fn):
  182. config_file = fn
  183. break
  184. else:
  185. raise DistutilsError('_numpyconfig.h not found in numpy include '
  186. 'dirs %r' % (dirs,))
  187. with open(config_file) as fid:
  188. mathlibs = []
  189. s = '#define MATHLIB'
  190. for line in fid:
  191. if line.startswith(s):
  192. value = line[len(s):].strip()
  193. if value:
  194. mathlibs.extend(value.split(','))
  195. return mathlibs
  196. def minrelpath(path):
  197. """Resolve `..` and '.' from path.
  198. """
  199. if not is_string(path):
  200. return path
  201. if '.' not in path:
  202. return path
  203. l = path.split(os.sep)
  204. while l:
  205. try:
  206. i = l.index('.', 1)
  207. except ValueError:
  208. break
  209. del l[i]
  210. j = 1
  211. while l:
  212. try:
  213. i = l.index('..', j)
  214. except ValueError:
  215. break
  216. if l[i-1]=='..':
  217. j += 1
  218. else:
  219. del l[i], l[i-1]
  220. j = 1
  221. if not l:
  222. return ''
  223. return os.sep.join(l)
  224. def sorted_glob(fileglob):
  225. """sorts output of python glob for https://bugs.python.org/issue30461
  226. to allow extensions to have reproducible build results"""
  227. return sorted(glob.glob(fileglob))
  228. def _fix_paths(paths, local_path, include_non_existing):
  229. assert is_sequence(paths), repr(type(paths))
  230. new_paths = []
  231. assert not is_string(paths), repr(paths)
  232. for n in paths:
  233. if is_string(n):
  234. if '*' in n or '?' in n:
  235. p = sorted_glob(n)
  236. p2 = sorted_glob(njoin(local_path, n))
  237. if p2:
  238. new_paths.extend(p2)
  239. elif p:
  240. new_paths.extend(p)
  241. else:
  242. if include_non_existing:
  243. new_paths.append(n)
  244. print('could not resolve pattern in %r: %r' %
  245. (local_path, n))
  246. else:
  247. n2 = njoin(local_path, n)
  248. if os.path.exists(n2):
  249. new_paths.append(n2)
  250. else:
  251. if os.path.exists(n):
  252. new_paths.append(n)
  253. elif include_non_existing:
  254. new_paths.append(n)
  255. if not os.path.exists(n):
  256. print('non-existing path in %r: %r' %
  257. (local_path, n))
  258. elif is_sequence(n):
  259. new_paths.extend(_fix_paths(n, local_path, include_non_existing))
  260. else:
  261. new_paths.append(n)
  262. return [minrelpath(p) for p in new_paths]
  263. def gpaths(paths, local_path='', include_non_existing=True):
  264. """Apply glob to paths and prepend local_path if needed.
  265. """
  266. if is_string(paths):
  267. paths = (paths,)
  268. return _fix_paths(paths, local_path, include_non_existing)
  269. def make_temp_file(suffix='', prefix='', text=True):
  270. if not hasattr(_tdata, 'tempdir'):
  271. _tdata.tempdir = tempfile.mkdtemp()
  272. _tmpdirs.append(_tdata.tempdir)
  273. fid, name = tempfile.mkstemp(suffix=suffix,
  274. prefix=prefix,
  275. dir=_tdata.tempdir,
  276. text=text)
  277. fo = os.fdopen(fid, 'w')
  278. return fo, name
  279. # Hooks for colored terminal output.
  280. # See also https://web.archive.org/web/20100314204946/http://www.livinglogic.de/Python/ansistyle
  281. def terminal_has_colors():
  282. if sys.platform=='cygwin' and 'USE_COLOR' not in os.environ:
  283. # Avoid importing curses that causes illegal operation
  284. # with a message:
  285. # PYTHON2 caused an invalid page fault in
  286. # module CYGNURSES7.DLL as 015f:18bbfc28
  287. # Details: Python 2.3.3 [GCC 3.3.1 (cygming special)]
  288. # ssh to Win32 machine from debian
  289. # curses.version is 2.2
  290. # CYGWIN_98-4.10, release 1.5.7(0.109/3/2))
  291. return 0
  292. if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
  293. try:
  294. import curses
  295. curses.setupterm()
  296. if (curses.tigetnum("colors") >= 0
  297. and curses.tigetnum("pairs") >= 0
  298. and ((curses.tigetstr("setf") is not None
  299. and curses.tigetstr("setb") is not None)
  300. or (curses.tigetstr("setaf") is not None
  301. and curses.tigetstr("setab") is not None)
  302. or curses.tigetstr("scp") is not None)):
  303. return 1
  304. except Exception:
  305. pass
  306. return 0
  307. if terminal_has_colors():
  308. _colour_codes = dict(black=0, red=1, green=2, yellow=3,
  309. blue=4, magenta=5, cyan=6, white=7, default=9)
  310. def colour_text(s, fg=None, bg=None, bold=False):
  311. seq = []
  312. if bold:
  313. seq.append('1')
  314. if fg:
  315. fgcode = 30 + _colour_codes.get(fg.lower(), 0)
  316. seq.append(str(fgcode))
  317. if bg:
  318. bgcode = 40 + _colour_codes.get(fg.lower(), 7)
  319. seq.append(str(bgcode))
  320. if seq:
  321. return '\x1b[%sm%s\x1b[0m' % (';'.join(seq), s)
  322. else:
  323. return s
  324. else:
  325. def colour_text(s, fg=None, bg=None):
  326. return s
  327. def default_text(s):
  328. return colour_text(s, 'default')
  329. def red_text(s):
  330. return colour_text(s, 'red')
  331. def green_text(s):
  332. return colour_text(s, 'green')
  333. def yellow_text(s):
  334. return colour_text(s, 'yellow')
  335. def cyan_text(s):
  336. return colour_text(s, 'cyan')
  337. def blue_text(s):
  338. return colour_text(s, 'blue')
  339. #########################
  340. def cyg2win32(path):
  341. if sys.platform=='cygwin' and path.startswith('/cygdrive'):
  342. path = path[10] + ':' + os.path.normcase(path[11:])
  343. return path
  344. def mingw32():
  345. """Return true when using mingw32 environment.
  346. """
  347. if sys.platform=='win32':
  348. if os.environ.get('OSTYPE', '')=='msys':
  349. return True
  350. if os.environ.get('MSYSTEM', '')=='MINGW32':
  351. return True
  352. return False
  353. def msvc_runtime_version():
  354. "Return version of MSVC runtime library, as defined by __MSC_VER__ macro"
  355. msc_pos = sys.version.find('MSC v.')
  356. if msc_pos != -1:
  357. msc_ver = int(sys.version[msc_pos+6:msc_pos+10])
  358. else:
  359. msc_ver = None
  360. return msc_ver
  361. def msvc_runtime_library():
  362. "Return name of MSVC runtime library if Python was built with MSVC >= 7"
  363. ver = msvc_runtime_major ()
  364. if ver:
  365. if ver < 140:
  366. return "msvcr%i" % ver
  367. else:
  368. return "vcruntime%i" % ver
  369. else:
  370. return None
  371. def msvc_runtime_major():
  372. "Return major version of MSVC runtime coded like get_build_msvc_version"
  373. major = {1300: 70, # MSVC 7.0
  374. 1310: 71, # MSVC 7.1
  375. 1400: 80, # MSVC 8
  376. 1500: 90, # MSVC 9 (aka 2008)
  377. 1600: 100, # MSVC 10 (aka 2010)
  378. 1900: 140, # MSVC 14 (aka 2015)
  379. }.get(msvc_runtime_version(), None)
  380. return major
  381. #########################
  382. #XXX need support for .C that is also C++
  383. cxx_ext_match = re.compile(r'.*\.(cpp|cxx|cc)\Z', re.I).match
  384. fortran_ext_match = re.compile(r'.*\.(f90|f95|f77|for|ftn|f)\Z', re.I).match
  385. f90_ext_match = re.compile(r'.*\.(f90|f95)\Z', re.I).match
  386. f90_module_name_match = re.compile(r'\s*module\s*(?P<name>[\w_]+)', re.I).match
  387. def _get_f90_modules(source):
  388. """Return a list of Fortran f90 module names that
  389. given source file defines.
  390. """
  391. if not f90_ext_match(source):
  392. return []
  393. modules = []
  394. with open(source, 'r') as f:
  395. for line in f:
  396. m = f90_module_name_match(line)
  397. if m:
  398. name = m.group('name')
  399. modules.append(name)
  400. # break # XXX can we assume that there is one module per file?
  401. return modules
  402. def is_string(s):
  403. return isinstance(s, str)
  404. def all_strings(lst):
  405. """Return True if all items in lst are string objects. """
  406. for item in lst:
  407. if not is_string(item):
  408. return False
  409. return True
  410. def is_sequence(seq):
  411. if is_string(seq):
  412. return False
  413. try:
  414. len(seq)
  415. except Exception:
  416. return False
  417. return True
  418. def is_glob_pattern(s):
  419. return is_string(s) and ('*' in s or '?' in s)
  420. def as_list(seq):
  421. if is_sequence(seq):
  422. return list(seq)
  423. else:
  424. return [seq]
  425. def get_language(sources):
  426. # not used in numpy/scipy packages, use build_ext.detect_language instead
  427. """Determine language value (c,f77,f90) from sources """
  428. language = None
  429. for source in sources:
  430. if isinstance(source, str):
  431. if f90_ext_match(source):
  432. language = 'f90'
  433. break
  434. elif fortran_ext_match(source):
  435. language = 'f77'
  436. return language
  437. def has_f_sources(sources):
  438. """Return True if sources contains Fortran files """
  439. for source in sources:
  440. if fortran_ext_match(source):
  441. return True
  442. return False
  443. def has_cxx_sources(sources):
  444. """Return True if sources contains C++ files """
  445. for source in sources:
  446. if cxx_ext_match(source):
  447. return True
  448. return False
  449. def filter_sources(sources):
  450. """Return four lists of filenames containing
  451. C, C++, Fortran, and Fortran 90 module sources,
  452. respectively.
  453. """
  454. c_sources = []
  455. cxx_sources = []
  456. f_sources = []
  457. fmodule_sources = []
  458. for source in sources:
  459. if fortran_ext_match(source):
  460. modules = _get_f90_modules(source)
  461. if modules:
  462. fmodule_sources.append(source)
  463. else:
  464. f_sources.append(source)
  465. elif cxx_ext_match(source):
  466. cxx_sources.append(source)
  467. else:
  468. c_sources.append(source)
  469. return c_sources, cxx_sources, f_sources, fmodule_sources
  470. def _get_headers(directory_list):
  471. # get *.h files from list of directories
  472. headers = []
  473. for d in directory_list:
  474. head = sorted_glob(os.path.join(d, "*.h")) #XXX: *.hpp files??
  475. headers.extend(head)
  476. return headers
  477. def _get_directories(list_of_sources):
  478. # get unique directories from list of sources.
  479. direcs = []
  480. for f in list_of_sources:
  481. d = os.path.split(f)
  482. if d[0] != '' and not d[0] in direcs:
  483. direcs.append(d[0])
  484. return direcs
  485. def _commandline_dep_string(cc_args, extra_postargs, pp_opts):
  486. """
  487. Return commandline representation used to determine if a file needs
  488. to be recompiled
  489. """
  490. cmdline = 'commandline: '
  491. cmdline += ' '.join(cc_args)
  492. cmdline += ' '.join(extra_postargs)
  493. cmdline += ' '.join(pp_opts) + '\n'
  494. return cmdline
  495. def get_dependencies(sources):
  496. #XXX scan sources for include statements
  497. return _get_headers(_get_directories(sources))
  498. def is_local_src_dir(directory):
  499. """Return true if directory is local directory.
  500. """
  501. if not is_string(directory):
  502. return False
  503. abs_dir = os.path.abspath(directory)
  504. c = os.path.commonprefix([os.getcwd(), abs_dir])
  505. new_dir = abs_dir[len(c):].split(os.sep)
  506. if new_dir and not new_dir[0]:
  507. new_dir = new_dir[1:]
  508. if new_dir and new_dir[0]=='build':
  509. return False
  510. new_dir = os.sep.join(new_dir)
  511. return os.path.isdir(new_dir)
  512. def general_source_files(top_path):
  513. pruned_directories = {'CVS':1, '.svn':1, 'build':1}
  514. prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
  515. for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
  516. pruned = [ d for d in dirnames if d not in pruned_directories ]
  517. dirnames[:] = pruned
  518. for f in filenames:
  519. if not prune_file_pat.search(f):
  520. yield os.path.join(dirpath, f)
  521. def general_source_directories_files(top_path):
  522. """Return a directory name relative to top_path and
  523. files contained.
  524. """
  525. pruned_directories = ['CVS', '.svn', 'build']
  526. prune_file_pat = re.compile(r'(?:[~#]|\.py[co]|\.o)$')
  527. for dirpath, dirnames, filenames in os.walk(top_path, topdown=True):
  528. pruned = [ d for d in dirnames if d not in pruned_directories ]
  529. dirnames[:] = pruned
  530. for d in dirnames:
  531. dpath = os.path.join(dirpath, d)
  532. rpath = rel_path(dpath, top_path)
  533. files = []
  534. for f in os.listdir(dpath):
  535. fn = os.path.join(dpath, f)
  536. if os.path.isfile(fn) and not prune_file_pat.search(fn):
  537. files.append(fn)
  538. yield rpath, files
  539. dpath = top_path
  540. rpath = rel_path(dpath, top_path)
  541. filenames = [os.path.join(dpath, f) for f in os.listdir(dpath) \
  542. if not prune_file_pat.search(f)]
  543. files = [f for f in filenames if os.path.isfile(f)]
  544. yield rpath, files
  545. def get_ext_source_files(ext):
  546. # Get sources and any include files in the same directory.
  547. filenames = []
  548. sources = [_m for _m in ext.sources if is_string(_m)]
  549. filenames.extend(sources)
  550. filenames.extend(get_dependencies(sources))
  551. for d in ext.depends:
  552. if is_local_src_dir(d):
  553. filenames.extend(list(general_source_files(d)))
  554. elif os.path.isfile(d):
  555. filenames.append(d)
  556. return filenames
  557. def get_script_files(scripts):
  558. scripts = [_m for _m in scripts if is_string(_m)]
  559. return scripts
  560. def get_lib_source_files(lib):
  561. filenames = []
  562. sources = lib[1].get('sources', [])
  563. sources = [_m for _m in sources if is_string(_m)]
  564. filenames.extend(sources)
  565. filenames.extend(get_dependencies(sources))
  566. depends = lib[1].get('depends', [])
  567. for d in depends:
  568. if is_local_src_dir(d):
  569. filenames.extend(list(general_source_files(d)))
  570. elif os.path.isfile(d):
  571. filenames.append(d)
  572. return filenames
  573. def get_shared_lib_extension(is_python_ext=False):
  574. """Return the correct file extension for shared libraries.
  575. Parameters
  576. ----------
  577. is_python_ext : bool, optional
  578. Whether the shared library is a Python extension. Default is False.
  579. Returns
  580. -------
  581. so_ext : str
  582. The shared library extension.
  583. Notes
  584. -----
  585. For Python shared libs, `so_ext` will typically be '.so' on Linux and OS X,
  586. and '.pyd' on Windows. For Python >= 3.2 `so_ext` has a tag prepended on
  587. POSIX systems according to PEP 3149. For Python 3.2 this is implemented on
  588. Linux, but not on OS X.
  589. """
  590. confvars = distutils.sysconfig.get_config_vars()
  591. # SO is deprecated in 3.3.1, use EXT_SUFFIX instead
  592. so_ext = confvars.get('EXT_SUFFIX', None)
  593. if so_ext is None:
  594. so_ext = confvars.get('SO', '')
  595. if not is_python_ext:
  596. # hardcode known values, config vars (including SHLIB_SUFFIX) are
  597. # unreliable (see #3182)
  598. # darwin, windows and debug linux are wrong in 3.3.1 and older
  599. if (sys.platform.startswith('linux') or
  600. sys.platform.startswith('gnukfreebsd')):
  601. so_ext = '.so'
  602. elif sys.platform.startswith('darwin'):
  603. so_ext = '.dylib'
  604. elif sys.platform.startswith('win'):
  605. so_ext = '.dll'
  606. else:
  607. # fall back to config vars for unknown platforms
  608. # fix long extension for Python >=3.2, see PEP 3149.
  609. if 'SOABI' in confvars:
  610. # Does nothing unless SOABI config var exists
  611. so_ext = so_ext.replace('.' + confvars.get('SOABI'), '', 1)
  612. return so_ext
  613. def get_data_files(data):
  614. if is_string(data):
  615. return [data]
  616. sources = data[1]
  617. filenames = []
  618. for s in sources:
  619. if hasattr(s, '__call__'):
  620. continue
  621. if is_local_src_dir(s):
  622. filenames.extend(list(general_source_files(s)))
  623. elif is_string(s):
  624. if os.path.isfile(s):
  625. filenames.append(s)
  626. else:
  627. print('Not existing data file:', s)
  628. else:
  629. raise TypeError(repr(s))
  630. return filenames
  631. def dot_join(*args):
  632. return '.'.join([a for a in args if a])
  633. def get_frame(level=0):
  634. """Return frame object from call stack with given level.
  635. """
  636. try:
  637. return sys._getframe(level+1)
  638. except AttributeError:
  639. frame = sys.exc_info()[2].tb_frame
  640. for _ in range(level+1):
  641. frame = frame.f_back
  642. return frame
  643. ######################
  644. class Configuration:
  645. _list_keys = ['packages', 'ext_modules', 'data_files', 'include_dirs',
  646. 'libraries', 'headers', 'scripts', 'py_modules',
  647. 'installed_libraries', 'define_macros']
  648. _dict_keys = ['package_dir', 'installed_pkg_config']
  649. _extra_keys = ['name', 'version']
  650. numpy_include_dirs = []
  651. def __init__(self,
  652. package_name=None,
  653. parent_name=None,
  654. top_path=None,
  655. package_path=None,
  656. caller_level=1,
  657. setup_name='setup.py',
  658. **attrs):
  659. """Construct configuration instance of a package.
  660. package_name -- name of the package
  661. Ex.: 'distutils'
  662. parent_name -- name of the parent package
  663. Ex.: 'numpy'
  664. top_path -- directory of the toplevel package
  665. Ex.: the directory where the numpy package source sits
  666. package_path -- directory of package. Will be computed by magic from the
  667. directory of the caller module if not specified
  668. Ex.: the directory where numpy.distutils is
  669. caller_level -- frame level to caller namespace, internal parameter.
  670. """
  671. self.name = dot_join(parent_name, package_name)
  672. self.version = None
  673. caller_frame = get_frame(caller_level)
  674. self.local_path = get_path_from_frame(caller_frame, top_path)
  675. # local_path -- directory of a file (usually setup.py) that
  676. # defines a configuration() function.
  677. # local_path -- directory of a file (usually setup.py) that
  678. # defines a configuration() function.
  679. if top_path is None:
  680. top_path = self.local_path
  681. self.local_path = ''
  682. if package_path is None:
  683. package_path = self.local_path
  684. elif os.path.isdir(njoin(self.local_path, package_path)):
  685. package_path = njoin(self.local_path, package_path)
  686. if not os.path.isdir(package_path or '.'):
  687. raise ValueError("%r is not a directory" % (package_path,))
  688. self.top_path = top_path
  689. self.package_path = package_path
  690. # this is the relative path in the installed package
  691. self.path_in_package = os.path.join(*self.name.split('.'))
  692. self.list_keys = self._list_keys[:]
  693. self.dict_keys = self._dict_keys[:]
  694. for n in self.list_keys:
  695. v = copy.copy(attrs.get(n, []))
  696. setattr(self, n, as_list(v))
  697. for n in self.dict_keys:
  698. v = copy.copy(attrs.get(n, {}))
  699. setattr(self, n, v)
  700. known_keys = self.list_keys + self.dict_keys
  701. self.extra_keys = self._extra_keys[:]
  702. for n in attrs.keys():
  703. if n in known_keys:
  704. continue
  705. a = attrs[n]
  706. setattr(self, n, a)
  707. if isinstance(a, list):
  708. self.list_keys.append(n)
  709. elif isinstance(a, dict):
  710. self.dict_keys.append(n)
  711. else:
  712. self.extra_keys.append(n)
  713. if os.path.exists(njoin(package_path, '__init__.py')):
  714. self.packages.append(self.name)
  715. self.package_dir[self.name] = package_path
  716. self.options = dict(
  717. ignore_setup_xxx_py = False,
  718. assume_default_configuration = False,
  719. delegate_options_to_subpackages = False,
  720. quiet = False,
  721. )
  722. caller_instance = None
  723. for i in range(1, 3):
  724. try:
  725. f = get_frame(i)
  726. except ValueError:
  727. break
  728. try:
  729. caller_instance = eval('self', f.f_globals, f.f_locals)
  730. break
  731. except NameError:
  732. pass
  733. if isinstance(caller_instance, self.__class__):
  734. if caller_instance.options['delegate_options_to_subpackages']:
  735. self.set_options(**caller_instance.options)
  736. self.setup_name = setup_name
  737. def todict(self):
  738. """
  739. Return a dictionary compatible with the keyword arguments of distutils
  740. setup function.
  741. Examples
  742. --------
  743. >>> setup(**config.todict()) #doctest: +SKIP
  744. """
  745. self._optimize_data_files()
  746. d = {}
  747. known_keys = self.list_keys + self.dict_keys + self.extra_keys
  748. for n in known_keys:
  749. a = getattr(self, n)
  750. if a:
  751. d[n] = a
  752. return d
  753. def info(self, message):
  754. if not self.options['quiet']:
  755. print(message)
  756. def warn(self, message):
  757. sys.stderr.write('Warning: %s\n' % (message,))
  758. def set_options(self, **options):
  759. """
  760. Configure Configuration instance.
  761. The following options are available:
  762. - ignore_setup_xxx_py
  763. - assume_default_configuration
  764. - delegate_options_to_subpackages
  765. - quiet
  766. """
  767. for key, value in options.items():
  768. if key in self.options:
  769. self.options[key] = value
  770. else:
  771. raise ValueError('Unknown option: '+key)
  772. def get_distribution(self):
  773. """Return the distutils distribution object for self."""
  774. from numpy.distutils.core import get_distribution
  775. return get_distribution()
  776. def _wildcard_get_subpackage(self, subpackage_name,
  777. parent_name,
  778. caller_level = 1):
  779. l = subpackage_name.split('.')
  780. subpackage_path = njoin([self.local_path]+l)
  781. dirs = [_m for _m in sorted_glob(subpackage_path) if os.path.isdir(_m)]
  782. config_list = []
  783. for d in dirs:
  784. if not os.path.isfile(njoin(d, '__init__.py')):
  785. continue
  786. if 'build' in d.split(os.sep):
  787. continue
  788. n = '.'.join(d.split(os.sep)[-len(l):])
  789. c = self.get_subpackage(n,
  790. parent_name = parent_name,
  791. caller_level = caller_level+1)
  792. config_list.extend(c)
  793. return config_list
  794. def _get_configuration_from_setup_py(self, setup_py,
  795. subpackage_name,
  796. subpackage_path,
  797. parent_name,
  798. caller_level = 1):
  799. # In case setup_py imports local modules:
  800. sys.path.insert(0, os.path.dirname(setup_py))
  801. try:
  802. setup_name = os.path.splitext(os.path.basename(setup_py))[0]
  803. n = dot_join(self.name, subpackage_name, setup_name)
  804. setup_module = exec_mod_from_location(
  805. '_'.join(n.split('.')), setup_py)
  806. if not hasattr(setup_module, 'configuration'):
  807. if not self.options['assume_default_configuration']:
  808. self.warn('Assuming default configuration '\
  809. '(%s does not define configuration())'\
  810. % (setup_module))
  811. config = Configuration(subpackage_name, parent_name,
  812. self.top_path, subpackage_path,
  813. caller_level = caller_level + 1)
  814. else:
  815. pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1]))
  816. args = (pn,)
  817. if setup_module.configuration.__code__.co_argcount > 1:
  818. args = args + (self.top_path,)
  819. config = setup_module.configuration(*args)
  820. if config.name!=dot_join(parent_name, subpackage_name):
  821. self.warn('Subpackage %r configuration returned as %r' % \
  822. (dot_join(parent_name, subpackage_name), config.name))
  823. finally:
  824. del sys.path[0]
  825. return config
  826. def get_subpackage(self,subpackage_name,
  827. subpackage_path=None,
  828. parent_name=None,
  829. caller_level = 1):
  830. """Return list of subpackage configurations.
  831. Parameters
  832. ----------
  833. subpackage_name : str or None
  834. Name of the subpackage to get the configuration. '*' in
  835. subpackage_name is handled as a wildcard.
  836. subpackage_path : str
  837. If None, then the path is assumed to be the local path plus the
  838. subpackage_name. If a setup.py file is not found in the
  839. subpackage_path, then a default configuration is used.
  840. parent_name : str
  841. Parent name.
  842. """
  843. if subpackage_name is None:
  844. if subpackage_path is None:
  845. raise ValueError(
  846. "either subpackage_name or subpackage_path must be specified")
  847. subpackage_name = os.path.basename(subpackage_path)
  848. # handle wildcards
  849. l = subpackage_name.split('.')
  850. if subpackage_path is None and '*' in subpackage_name:
  851. return self._wildcard_get_subpackage(subpackage_name,
  852. parent_name,
  853. caller_level = caller_level+1)
  854. assert '*' not in subpackage_name, repr((subpackage_name, subpackage_path, parent_name))
  855. if subpackage_path is None:
  856. subpackage_path = njoin([self.local_path] + l)
  857. else:
  858. subpackage_path = njoin([subpackage_path] + l[:-1])
  859. subpackage_path = self.paths([subpackage_path])[0]
  860. setup_py = njoin(subpackage_path, self.setup_name)
  861. if not self.options['ignore_setup_xxx_py']:
  862. if not os.path.isfile(setup_py):
  863. setup_py = njoin(subpackage_path,
  864. 'setup_%s.py' % (subpackage_name))
  865. if not os.path.isfile(setup_py):
  866. if not self.options['assume_default_configuration']:
  867. self.warn('Assuming default configuration '\
  868. '(%s/{setup_%s,setup}.py was not found)' \
  869. % (os.path.dirname(setup_py), subpackage_name))
  870. config = Configuration(subpackage_name, parent_name,
  871. self.top_path, subpackage_path,
  872. caller_level = caller_level+1)
  873. else:
  874. config = self._get_configuration_from_setup_py(
  875. setup_py,
  876. subpackage_name,
  877. subpackage_path,
  878. parent_name,
  879. caller_level = caller_level + 1)
  880. if config:
  881. return [config]
  882. else:
  883. return []
  884. def add_subpackage(self,subpackage_name,
  885. subpackage_path=None,
  886. standalone = False):
  887. """Add a sub-package to the current Configuration instance.
  888. This is useful in a setup.py script for adding sub-packages to a
  889. package.
  890. Parameters
  891. ----------
  892. subpackage_name : str
  893. name of the subpackage
  894. subpackage_path : str
  895. if given, the subpackage path such as the subpackage is in
  896. subpackage_path / subpackage_name. If None,the subpackage is
  897. assumed to be located in the local path / subpackage_name.
  898. standalone : bool
  899. """
  900. if standalone:
  901. parent_name = None
  902. else:
  903. parent_name = self.name
  904. config_list = self.get_subpackage(subpackage_name, subpackage_path,
  905. parent_name = parent_name,
  906. caller_level = 2)
  907. if not config_list:
  908. self.warn('No configuration returned, assuming unavailable.')
  909. for config in config_list:
  910. d = config
  911. if isinstance(config, Configuration):
  912. d = config.todict()
  913. assert isinstance(d, dict), repr(type(d))
  914. self.info('Appending %s configuration to %s' \
  915. % (d.get('name'), self.name))
  916. self.dict_append(**d)
  917. dist = self.get_distribution()
  918. if dist is not None:
  919. self.warn('distutils distribution has been initialized,'\
  920. ' it may be too late to add a subpackage '+ subpackage_name)
  921. def add_data_dir(self, data_path):
  922. """Recursively add files under data_path to data_files list.
  923. Recursively add files under data_path to the list of data_files to be
  924. installed (and distributed). The data_path can be either a relative
  925. path-name, or an absolute path-name, or a 2-tuple where the first
  926. argument shows where in the install directory the data directory
  927. should be installed to.
  928. Parameters
  929. ----------
  930. data_path : seq or str
  931. Argument can be either
  932. * 2-sequence (<datadir suffix>, <path to data directory>)
  933. * path to data directory where python datadir suffix defaults
  934. to package dir.
  935. Notes
  936. -----
  937. Rules for installation paths::
  938. foo/bar -> (foo/bar, foo/bar) -> parent/foo/bar
  939. (gun, foo/bar) -> parent/gun
  940. foo/* -> (foo/a, foo/a), (foo/b, foo/b) -> parent/foo/a, parent/foo/b
  941. (gun, foo/*) -> (gun, foo/a), (gun, foo/b) -> gun
  942. (gun/*, foo/*) -> parent/gun/a, parent/gun/b
  943. /foo/bar -> (bar, /foo/bar) -> parent/bar
  944. (gun, /foo/bar) -> parent/gun
  945. (fun/*/gun/*, sun/foo/bar) -> parent/fun/foo/gun/bar
  946. Examples
  947. --------
  948. For example suppose the source directory contains fun/foo.dat and
  949. fun/bar/car.dat:
  950. >>> self.add_data_dir('fun') #doctest: +SKIP
  951. >>> self.add_data_dir(('sun', 'fun')) #doctest: +SKIP
  952. >>> self.add_data_dir(('gun', '/full/path/to/fun'))#doctest: +SKIP
  953. Will install data-files to the locations::
  954. <package install directory>/
  955. fun/
  956. foo.dat
  957. bar/
  958. car.dat
  959. sun/
  960. foo.dat
  961. bar/
  962. car.dat
  963. gun/
  964. foo.dat
  965. car.dat
  966. """
  967. if is_sequence(data_path):
  968. d, data_path = data_path
  969. else:
  970. d = None
  971. if is_sequence(data_path):
  972. [self.add_data_dir((d, p)) for p in data_path]
  973. return
  974. if not is_string(data_path):
  975. raise TypeError("not a string: %r" % (data_path,))
  976. if d is None:
  977. if os.path.isabs(data_path):
  978. return self.add_data_dir((os.path.basename(data_path), data_path))
  979. return self.add_data_dir((data_path, data_path))
  980. paths = self.paths(data_path, include_non_existing=False)
  981. if is_glob_pattern(data_path):
  982. if is_glob_pattern(d):
  983. pattern_list = allpath(d).split(os.sep)
  984. pattern_list.reverse()
  985. # /a/*//b/ -> /a/*/b
  986. rl = list(range(len(pattern_list)-1)); rl.reverse()
  987. for i in rl:
  988. if not pattern_list[i]:
  989. del pattern_list[i]
  990. #
  991. for path in paths:
  992. if not os.path.isdir(path):
  993. print('Not a directory, skipping', path)
  994. continue
  995. rpath = rel_path(path, self.local_path)
  996. path_list = rpath.split(os.sep)
  997. path_list.reverse()
  998. target_list = []
  999. i = 0
  1000. for s in pattern_list:
  1001. if is_glob_pattern(s):
  1002. if i>=len(path_list):
  1003. raise ValueError('cannot fill pattern %r with %r' \
  1004. % (d, path))
  1005. target_list.append(path_list[i])
  1006. else:
  1007. assert s==path_list[i], repr((s, path_list[i], data_path, d, path, rpath))
  1008. target_list.append(s)
  1009. i += 1
  1010. if path_list[i:]:
  1011. self.warn('mismatch of pattern_list=%s and path_list=%s'\
  1012. % (pattern_list, path_list))
  1013. target_list.reverse()
  1014. self.add_data_dir((os.sep.join(target_list), path))
  1015. else:
  1016. for path in paths:
  1017. self.add_data_dir((d, path))
  1018. return
  1019. assert not is_glob_pattern(d), repr(d)
  1020. dist = self.get_distribution()
  1021. if dist is not None and dist.data_files is not None:
  1022. data_files = dist.data_files
  1023. else:
  1024. data_files = self.data_files
  1025. for path in paths:
  1026. for d1, f in list(general_source_directories_files(path)):
  1027. target_path = os.path.join(self.path_in_package, d, d1)
  1028. data_files.append((target_path, f))
  1029. def _optimize_data_files(self):
  1030. data_dict = {}
  1031. for p, files in self.data_files:
  1032. if p not in data_dict:
  1033. data_dict[p] = set()
  1034. for f in files:
  1035. data_dict[p].add(f)
  1036. self.data_files[:] = [(p, list(files)) for p, files in data_dict.items()]
  1037. def add_data_files(self,*files):
  1038. """Add data files to configuration data_files.
  1039. Parameters
  1040. ----------
  1041. files : sequence
  1042. Argument(s) can be either
  1043. * 2-sequence (<datadir prefix>,<path to data file(s)>)
  1044. * paths to data files where python datadir prefix defaults
  1045. to package dir.
  1046. Notes
  1047. -----
  1048. The form of each element of the files sequence is very flexible
  1049. allowing many combinations of where to get the files from the package
  1050. and where they should ultimately be installed on the system. The most
  1051. basic usage is for an element of the files argument sequence to be a
  1052. simple filename. This will cause that file from the local path to be
  1053. installed to the installation path of the self.name package (package
  1054. path). The file argument can also be a relative path in which case the
  1055. entire relative path will be installed into the package directory.
  1056. Finally, the file can be an absolute path name in which case the file
  1057. will be found at the absolute path name but installed to the package
  1058. path.
  1059. This basic behavior can be augmented by passing a 2-tuple in as the
  1060. file argument. The first element of the tuple should specify the
  1061. relative path (under the package install directory) where the
  1062. remaining sequence of files should be installed to (it has nothing to
  1063. do with the file-names in the source distribution). The second element
  1064. of the tuple is the sequence of files that should be installed. The
  1065. files in this sequence can be filenames, relative paths, or absolute
  1066. paths. For absolute paths the file will be installed in the top-level
  1067. package installation directory (regardless of the first argument).
  1068. Filenames and relative path names will be installed in the package
  1069. install directory under the path name given as the first element of
  1070. the tuple.
  1071. Rules for installation paths:
  1072. #. file.txt -> (., file.txt)-> parent/file.txt
  1073. #. foo/file.txt -> (foo, foo/file.txt) -> parent/foo/file.txt
  1074. #. /foo/bar/file.txt -> (., /foo/bar/file.txt) -> parent/file.txt
  1075. #. ``*``.txt -> parent/a.txt, parent/b.txt
  1076. #. foo/``*``.txt`` -> parent/foo/a.txt, parent/foo/b.txt
  1077. #. ``*/*.txt`` -> (``*``, ``*``/``*``.txt) -> parent/c/a.txt, parent/d/b.txt
  1078. #. (sun, file.txt) -> parent/sun/file.txt
  1079. #. (sun, bar/file.txt) -> parent/sun/file.txt
  1080. #. (sun, /foo/bar/file.txt) -> parent/sun/file.txt
  1081. #. (sun, ``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
  1082. #. (sun, bar/``*``.txt) -> parent/sun/a.txt, parent/sun/b.txt
  1083. #. (sun/``*``, ``*``/``*``.txt) -> parent/sun/c/a.txt, parent/d/b.txt
  1084. An additional feature is that the path to a data-file can actually be
  1085. a function that takes no arguments and returns the actual path(s) to
  1086. the data-files. This is useful when the data files are generated while
  1087. building the package.
  1088. Examples
  1089. --------
  1090. Add files to the list of data_files to be included with the package.
  1091. >>> self.add_data_files('foo.dat',
  1092. ... ('fun', ['gun.dat', 'nun/pun.dat', '/tmp/sun.dat']),
  1093. ... 'bar/cat.dat',
  1094. ... '/full/path/to/can.dat') #doctest: +SKIP
  1095. will install these data files to::
  1096. <package install directory>/
  1097. foo.dat
  1098. fun/
  1099. gun.dat
  1100. nun/
  1101. pun.dat
  1102. sun.dat
  1103. bar/
  1104. car.dat
  1105. can.dat
  1106. where <package install directory> is the package (or sub-package)
  1107. directory such as '/usr/lib/python2.4/site-packages/mypackage' ('C:
  1108. \\Python2.4 \\Lib \\site-packages \\mypackage') or
  1109. '/usr/lib/python2.4/site- packages/mypackage/mysubpackage' ('C:
  1110. \\Python2.4 \\Lib \\site-packages \\mypackage \\mysubpackage').
  1111. """
  1112. if len(files)>1:
  1113. for f in files:
  1114. self.add_data_files(f)
  1115. return
  1116. assert len(files)==1
  1117. if is_sequence(files[0]):
  1118. d, files = files[0]
  1119. else:
  1120. d = None
  1121. if is_string(files):
  1122. filepat = files
  1123. elif is_sequence(files):
  1124. if len(files)==1:
  1125. filepat = files[0]
  1126. else:
  1127. for f in files:
  1128. self.add_data_files((d, f))
  1129. return
  1130. else:
  1131. raise TypeError(repr(type(files)))
  1132. if d is None:
  1133. if hasattr(filepat, '__call__'):
  1134. d = ''
  1135. elif os.path.isabs(filepat):
  1136. d = ''
  1137. else:
  1138. d = os.path.dirname(filepat)
  1139. self.add_data_files((d, files))
  1140. return
  1141. paths = self.paths(filepat, include_non_existing=False)
  1142. if is_glob_pattern(filepat):
  1143. if is_glob_pattern(d):
  1144. pattern_list = d.split(os.sep)
  1145. pattern_list.reverse()
  1146. for path in paths:
  1147. path_list = path.split(os.sep)
  1148. path_list.reverse()
  1149. path_list.pop() # filename
  1150. target_list = []
  1151. i = 0
  1152. for s in pattern_list:
  1153. if is_glob_pattern(s):
  1154. target_list.append(path_list[i])
  1155. i += 1
  1156. else:
  1157. target_list.append(s)
  1158. target_list.reverse()
  1159. self.add_data_files((os.sep.join(target_list), path))
  1160. else:
  1161. self.add_data_files((d, paths))
  1162. return
  1163. assert not is_glob_pattern(d), repr((d, filepat))
  1164. dist = self.get_distribution()
  1165. if dist is not None and dist.data_files is not None:
  1166. data_files = dist.data_files
  1167. else:
  1168. data_files = self.data_files
  1169. data_files.append((os.path.join(self.path_in_package, d), paths))
  1170. ### XXX Implement add_py_modules
  1171. def add_define_macros(self, macros):
  1172. """Add define macros to configuration
  1173. Add the given sequence of macro name and value duples to the beginning
  1174. of the define_macros list This list will be visible to all extension
  1175. modules of the current package.
  1176. """
  1177. dist = self.get_distribution()
  1178. if dist is not None:
  1179. if not hasattr(dist, 'define_macros'):
  1180. dist.define_macros = []
  1181. dist.define_macros.extend(macros)
  1182. else:
  1183. self.define_macros.extend(macros)
  1184. def add_include_dirs(self,*paths):
  1185. """Add paths to configuration include directories.
  1186. Add the given sequence of paths to the beginning of the include_dirs
  1187. list. This list will be visible to all extension modules of the
  1188. current package.
  1189. """
  1190. include_dirs = self.paths(paths)
  1191. dist = self.get_distribution()
  1192. if dist is not None:
  1193. if dist.include_dirs is None:
  1194. dist.include_dirs = []
  1195. dist.include_dirs.extend(include_dirs)
  1196. else:
  1197. self.include_dirs.extend(include_dirs)
  1198. def add_headers(self,*files):
  1199. """Add installable headers to configuration.
  1200. Add the given sequence of files to the beginning of the headers list.
  1201. By default, headers will be installed under <python-
  1202. include>/<self.name.replace('.','/')>/ directory. If an item of files
  1203. is a tuple, then its first argument specifies the actual installation
  1204. location relative to the <python-include> path.
  1205. Parameters
  1206. ----------
  1207. files : str or seq
  1208. Argument(s) can be either:
  1209. * 2-sequence (<includedir suffix>,<path to header file(s)>)
  1210. * path(s) to header file(s) where python includedir suffix will
  1211. default to package name.
  1212. """
  1213. headers = []
  1214. for path in files:
  1215. if is_string(path):
  1216. [headers.append((self.name, p)) for p in self.paths(path)]
  1217. else:
  1218. if not isinstance(path, (tuple, list)) or len(path) != 2:
  1219. raise TypeError(repr(path))
  1220. [headers.append((path[0], p)) for p in self.paths(path[1])]
  1221. dist = self.get_distribution()
  1222. if dist is not None:
  1223. if dist.headers is None:
  1224. dist.headers = []
  1225. dist.headers.extend(headers)
  1226. else:
  1227. self.headers.extend(headers)
  1228. def paths(self,*paths,**kws):
  1229. """Apply glob to paths and prepend local_path if needed.
  1230. Applies glob.glob(...) to each path in the sequence (if needed) and
  1231. pre-pends the local_path if needed. Because this is called on all
  1232. source lists, this allows wildcard characters to be specified in lists
  1233. of sources for extension modules and libraries and scripts and allows
  1234. path-names be relative to the source directory.
  1235. """
  1236. include_non_existing = kws.get('include_non_existing', True)
  1237. return gpaths(paths,
  1238. local_path = self.local_path,
  1239. include_non_existing=include_non_existing)
  1240. def _fix_paths_dict(self, kw):
  1241. for k in kw.keys():
  1242. v = kw[k]
  1243. if k in ['sources', 'depends', 'include_dirs', 'library_dirs',
  1244. 'module_dirs', 'extra_objects']:
  1245. new_v = self.paths(v)
  1246. kw[k] = new_v
  1247. def add_extension(self,name,sources,**kw):
  1248. """Add extension to configuration.
  1249. Create and add an Extension instance to the ext_modules list. This
  1250. method also takes the following optional keyword arguments that are
  1251. passed on to the Extension constructor.
  1252. Parameters
  1253. ----------
  1254. name : str
  1255. name of the extension
  1256. sources : seq
  1257. list of the sources. The list of sources may contain functions
  1258. (called source generators) which must take an extension instance
  1259. and a build directory as inputs and return a source file or list of
  1260. source files or None. If None is returned then no sources are
  1261. generated. If the Extension instance has no sources after
  1262. processing all source generators, then no extension module is
  1263. built.
  1264. include_dirs :
  1265. define_macros :
  1266. undef_macros :
  1267. library_dirs :
  1268. libraries :
  1269. runtime_library_dirs :
  1270. extra_objects :
  1271. extra_compile_args :
  1272. extra_link_args :
  1273. extra_f77_compile_args :
  1274. extra_f90_compile_args :
  1275. export_symbols :
  1276. swig_opts :
  1277. depends :
  1278. The depends list contains paths to files or directories that the
  1279. sources of the extension module depend on. If any path in the
  1280. depends list is newer than the extension module, then the module
  1281. will be rebuilt.
  1282. language :
  1283. f2py_options :
  1284. module_dirs :
  1285. extra_info : dict or list
  1286. dict or list of dict of keywords to be appended to keywords.
  1287. Notes
  1288. -----
  1289. The self.paths(...) method is applied to all lists that may contain
  1290. paths.
  1291. """
  1292. ext_args = copy.copy(kw)
  1293. ext_args['name'] = dot_join(self.name, name)
  1294. ext_args['sources'] = sources
  1295. if 'extra_info' in ext_args:
  1296. extra_info = ext_args['extra_info']
  1297. del ext_args['extra_info']
  1298. if isinstance(extra_info, dict):
  1299. extra_info = [extra_info]
  1300. for info in extra_info:
  1301. assert isinstance(info, dict), repr(info)
  1302. dict_append(ext_args,**info)
  1303. self._fix_paths_dict(ext_args)
  1304. # Resolve out-of-tree dependencies
  1305. libraries = ext_args.get('libraries', [])
  1306. libnames = []
  1307. ext_args['libraries'] = []
  1308. for libname in libraries:
  1309. if isinstance(libname, tuple):
  1310. self._fix_paths_dict(libname[1])
  1311. # Handle library names of the form libname@relative/path/to/library
  1312. if '@' in libname:
  1313. lname, lpath = libname.split('@', 1)
  1314. lpath = os.path.abspath(njoin(self.local_path, lpath))
  1315. if os.path.isdir(lpath):
  1316. c = self.get_subpackage(None, lpath,
  1317. caller_level = 2)
  1318. if isinstance(c, Configuration):
  1319. c = c.todict()
  1320. for l in [l[0] for l in c.get('libraries', [])]:
  1321. llname = l.split('__OF__', 1)[0]
  1322. if llname == lname:
  1323. c.pop('name', None)
  1324. dict_append(ext_args,**c)
  1325. break
  1326. continue
  1327. libnames.append(libname)
  1328. ext_args['libraries'] = libnames + ext_args['libraries']
  1329. ext_args['define_macros'] = \
  1330. self.define_macros + ext_args.get('define_macros', [])
  1331. from numpy.distutils.core import Extension
  1332. ext = Extension(**ext_args)
  1333. self.ext_modules.append(ext)
  1334. dist = self.get_distribution()
  1335. if dist is not None:
  1336. self.warn('distutils distribution has been initialized,'\
  1337. ' it may be too late to add an extension '+name)
  1338. return ext
  1339. def add_library(self,name,sources,**build_info):
  1340. """
  1341. Add library to configuration.
  1342. Parameters
  1343. ----------
  1344. name : str
  1345. Name of the extension.
  1346. sources : sequence
  1347. List of the sources. The list of sources may contain functions
  1348. (called source generators) which must take an extension instance
  1349. and a build directory as inputs and return a source file or list of
  1350. source files or None. If None is returned then no sources are
  1351. generated. If the Extension instance has no sources after
  1352. processing all source generators, then no extension module is
  1353. built.
  1354. build_info : dict, optional
  1355. The following keys are allowed:
  1356. * depends
  1357. * macros
  1358. * include_dirs
  1359. * extra_compiler_args
  1360. * extra_f77_compile_args
  1361. * extra_f90_compile_args
  1362. * f2py_options
  1363. * language
  1364. """
  1365. self._add_library(name, sources, None, build_info)
  1366. dist = self.get_distribution()
  1367. if dist is not None:
  1368. self.warn('distutils distribution has been initialized,'\
  1369. ' it may be too late to add a library '+ name)
  1370. def _add_library(self, name, sources, install_dir, build_info):
  1371. """Common implementation for add_library and add_installed_library. Do
  1372. not use directly"""
  1373. build_info = copy.copy(build_info)
  1374. build_info['sources'] = sources
  1375. # Sometimes, depends is not set up to an empty list by default, and if
  1376. # depends is not given to add_library, distutils barfs (#1134)
  1377. if not 'depends' in build_info:
  1378. build_info['depends'] = []
  1379. self._fix_paths_dict(build_info)
  1380. # Add to libraries list so that it is build with build_clib
  1381. self.libraries.append((name, build_info))
  1382. def add_installed_library(self, name, sources, install_dir, build_info=None):
  1383. """
  1384. Similar to add_library, but the specified library is installed.
  1385. Most C libraries used with `distutils` are only used to build python
  1386. extensions, but libraries built through this method will be installed
  1387. so that they can be reused by third-party packages.
  1388. Parameters
  1389. ----------
  1390. name : str
  1391. Name of the installed library.
  1392. sources : sequence
  1393. List of the library's source files. See `add_library` for details.
  1394. install_dir : str
  1395. Path to install the library, relative to the current sub-package.
  1396. build_info : dict, optional
  1397. The following keys are allowed:
  1398. * depends
  1399. * macros
  1400. * include_dirs
  1401. * extra_compiler_args
  1402. * extra_f77_compile_args
  1403. * extra_f90_compile_args
  1404. * f2py_options
  1405. * language
  1406. Returns
  1407. -------
  1408. None
  1409. See Also
  1410. --------
  1411. add_library, add_npy_pkg_config, get_info
  1412. Notes
  1413. -----
  1414. The best way to encode the options required to link against the specified
  1415. C libraries is to use a "libname.ini" file, and use `get_info` to
  1416. retrieve the required options (see `add_npy_pkg_config` for more
  1417. information).
  1418. """
  1419. if not build_info:
  1420. build_info = {}
  1421. install_dir = os.path.join(self.package_path, install_dir)
  1422. self._add_library(name, sources, install_dir, build_info)
  1423. self.installed_libraries.append(InstallableLib(name, build_info, install_dir))
  1424. def add_npy_pkg_config(self, template, install_dir, subst_dict=None):
  1425. """
  1426. Generate and install a npy-pkg config file from a template.
  1427. The config file generated from `template` is installed in the
  1428. given install directory, using `subst_dict` for variable substitution.
  1429. Parameters
  1430. ----------
  1431. template : str
  1432. The path of the template, relatively to the current package path.
  1433. install_dir : str
  1434. Where to install the npy-pkg config file, relatively to the current
  1435. package path.
  1436. subst_dict : dict, optional
  1437. If given, any string of the form ``@key@`` will be replaced by
  1438. ``subst_dict[key]`` in the template file when installed. The install
  1439. prefix is always available through the variable ``@prefix@``, since the
  1440. install prefix is not easy to get reliably from setup.py.
  1441. See also
  1442. --------
  1443. add_installed_library, get_info
  1444. Notes
  1445. -----
  1446. This works for both standard installs and in-place builds, i.e. the
  1447. ``@prefix@`` refer to the source directory for in-place builds.
  1448. Examples
  1449. --------
  1450. ::
  1451. config.add_npy_pkg_config('foo.ini.in', 'lib', {'foo': bar})
  1452. Assuming the foo.ini.in file has the following content::
  1453. [meta]
  1454. Name=@foo@
  1455. Version=1.0
  1456. Description=dummy description
  1457. [default]
  1458. Cflags=-I@prefix@/include
  1459. Libs=
  1460. The generated file will have the following content::
  1461. [meta]
  1462. Name=bar
  1463. Version=1.0
  1464. Description=dummy description
  1465. [default]
  1466. Cflags=-Iprefix_dir/include
  1467. Libs=
  1468. and will be installed as foo.ini in the 'lib' subpath.
  1469. When cross-compiling with numpy distutils, it might be necessary to
  1470. use modified npy-pkg-config files. Using the default/generated files
  1471. will link with the host libraries (i.e. libnpymath.a). For
  1472. cross-compilation you of-course need to link with target libraries,
  1473. while using the host Python installation.
  1474. You can copy out the numpy/core/lib/npy-pkg-config directory, add a
  1475. pkgdir value to the .ini files and set NPY_PKG_CONFIG_PATH environment
  1476. variable to point to the directory with the modified npy-pkg-config
  1477. files.
  1478. Example npymath.ini modified for cross-compilation::
  1479. [meta]
  1480. Name=npymath
  1481. Description=Portable, core math library implementing C99 standard
  1482. Version=0.1
  1483. [variables]
  1484. pkgname=numpy.core
  1485. pkgdir=/build/arm-linux-gnueabi/sysroot/usr/lib/python3.7/site-packages/numpy/core
  1486. prefix=${pkgdir}
  1487. libdir=${prefix}/lib
  1488. includedir=${prefix}/include
  1489. [default]
  1490. Libs=-L${libdir} -lnpymath
  1491. Cflags=-I${includedir}
  1492. Requires=mlib
  1493. [msvc]
  1494. Libs=/LIBPATH:${libdir} npymath.lib
  1495. Cflags=/INCLUDE:${includedir}
  1496. Requires=mlib
  1497. """
  1498. if subst_dict is None:
  1499. subst_dict = {}
  1500. template = os.path.join(self.package_path, template)
  1501. if self.name in self.installed_pkg_config:
  1502. self.installed_pkg_config[self.name].append((template, install_dir,
  1503. subst_dict))
  1504. else:
  1505. self.installed_pkg_config[self.name] = [(template, install_dir,
  1506. subst_dict)]
  1507. def add_scripts(self,*files):
  1508. """Add scripts to configuration.
  1509. Add the sequence of files to the beginning of the scripts list.
  1510. Scripts will be installed under the <prefix>/bin/ directory.
  1511. """
  1512. scripts = self.paths(files)
  1513. dist = self.get_distribution()
  1514. if dist is not None:
  1515. if dist.scripts is None:
  1516. dist.scripts = []
  1517. dist.scripts.extend(scripts)
  1518. else:
  1519. self.scripts.extend(scripts)
  1520. def dict_append(self,**dict):
  1521. for key in self.list_keys:
  1522. a = getattr(self, key)
  1523. a.extend(dict.get(key, []))
  1524. for key in self.dict_keys:
  1525. a = getattr(self, key)
  1526. a.update(dict.get(key, {}))
  1527. known_keys = self.list_keys + self.dict_keys + self.extra_keys
  1528. for key in dict.keys():
  1529. if key not in known_keys:
  1530. a = getattr(self, key, None)
  1531. if a and a==dict[key]: continue
  1532. self.warn('Inheriting attribute %r=%r from %r' \
  1533. % (key, dict[key], dict.get('name', '?')))
  1534. setattr(self, key, dict[key])
  1535. self.extra_keys.append(key)
  1536. elif key in self.extra_keys:
  1537. self.info('Ignoring attempt to set %r (from %r to %r)' \
  1538. % (key, getattr(self, key), dict[key]))
  1539. elif key in known_keys:
  1540. # key is already processed above
  1541. pass
  1542. else:
  1543. raise ValueError("Don't know about key=%r" % (key))
  1544. def __str__(self):
  1545. from pprint import pformat
  1546. known_keys = self.list_keys + self.dict_keys + self.extra_keys
  1547. s = '<'+5*'-' + '\n'
  1548. s += 'Configuration of '+self.name+':\n'
  1549. known_keys.sort()
  1550. for k in known_keys:
  1551. a = getattr(self, k, None)
  1552. if a:
  1553. s += '%s = %s\n' % (k, pformat(a))
  1554. s += 5*'-' + '>'
  1555. return s
  1556. def get_config_cmd(self):
  1557. """
  1558. Returns the numpy.distutils config command instance.
  1559. """
  1560. cmd = get_cmd('config')
  1561. cmd.ensure_finalized()
  1562. cmd.dump_source = 0
  1563. cmd.noisy = 0
  1564. old_path = os.environ.get('PATH')
  1565. if old_path:
  1566. path = os.pathsep.join(['.', old_path])
  1567. os.environ['PATH'] = path
  1568. return cmd
  1569. def get_build_temp_dir(self):
  1570. """
  1571. Return a path to a temporary directory where temporary files should be
  1572. placed.
  1573. """
  1574. cmd = get_cmd('build')
  1575. cmd.ensure_finalized()
  1576. return cmd.build_temp
  1577. def have_f77c(self):
  1578. """Check for availability of Fortran 77 compiler.
  1579. Use it inside source generating function to ensure that
  1580. setup distribution instance has been initialized.
  1581. Notes
  1582. -----
  1583. True if a Fortran 77 compiler is available (because a simple Fortran 77
  1584. code was able to be compiled successfully).
  1585. """
  1586. simple_fortran_subroutine = '''
  1587. subroutine simple
  1588. end
  1589. '''
  1590. config_cmd = self.get_config_cmd()
  1591. flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f77')
  1592. return flag
  1593. def have_f90c(self):
  1594. """Check for availability of Fortran 90 compiler.
  1595. Use it inside source generating function to ensure that
  1596. setup distribution instance has been initialized.
  1597. Notes
  1598. -----
  1599. True if a Fortran 90 compiler is available (because a simple Fortran
  1600. 90 code was able to be compiled successfully)
  1601. """
  1602. simple_fortran_subroutine = '''
  1603. subroutine simple
  1604. end
  1605. '''
  1606. config_cmd = self.get_config_cmd()
  1607. flag = config_cmd.try_compile(simple_fortran_subroutine, lang='f90')
  1608. return flag
  1609. def append_to(self, extlib):
  1610. """Append libraries, include_dirs to extension or library item.
  1611. """
  1612. if is_sequence(extlib):
  1613. lib_name, build_info = extlib
  1614. dict_append(build_info,
  1615. libraries=self.libraries,
  1616. include_dirs=self.include_dirs)
  1617. else:
  1618. from numpy.distutils.core import Extension
  1619. assert isinstance(extlib, Extension), repr(extlib)
  1620. extlib.libraries.extend(self.libraries)
  1621. extlib.include_dirs.extend(self.include_dirs)
  1622. def _get_svn_revision(self, path):
  1623. """Return path's SVN revision number.
  1624. """
  1625. try:
  1626. output = subprocess.check_output(['svnversion'], cwd=path)
  1627. except (subprocess.CalledProcessError, OSError):
  1628. pass
  1629. else:
  1630. m = re.match(rb'(?P<revision>\d+)', output)
  1631. if m:
  1632. return int(m.group('revision'))
  1633. if sys.platform=='win32' and os.environ.get('SVN_ASP_DOT_NET_HACK', None):
  1634. entries = njoin(path, '_svn', 'entries')
  1635. else:
  1636. entries = njoin(path, '.svn', 'entries')
  1637. if os.path.isfile(entries):
  1638. with open(entries) as f:
  1639. fstr = f.read()
  1640. if fstr[:5] == '<?xml': # pre 1.4
  1641. m = re.search(r'revision="(?P<revision>\d+)"', fstr)
  1642. if m:
  1643. return int(m.group('revision'))
  1644. else: # non-xml entries file --- check to be sure that
  1645. m = re.search(r'dir[\n\r]+(?P<revision>\d+)', fstr)
  1646. if m:
  1647. return int(m.group('revision'))
  1648. return None
  1649. def _get_hg_revision(self, path):
  1650. """Return path's Mercurial revision number.
  1651. """
  1652. try:
  1653. output = subprocess.check_output(
  1654. ['hg', 'identify', '--num'], cwd=path)
  1655. except (subprocess.CalledProcessError, OSError):
  1656. pass
  1657. else:
  1658. m = re.match(rb'(?P<revision>\d+)', output)
  1659. if m:
  1660. return int(m.group('revision'))
  1661. branch_fn = njoin(path, '.hg', 'branch')
  1662. branch_cache_fn = njoin(path, '.hg', 'branch.cache')
  1663. if os.path.isfile(branch_fn):
  1664. branch0 = None
  1665. with open(branch_fn) as f:
  1666. revision0 = f.read().strip()
  1667. branch_map = {}
  1668. with open(branch_cache_fn, 'r') as f:
  1669. for line in f:
  1670. branch1, revision1 = line.split()[:2]
  1671. if revision1==revision0:
  1672. branch0 = branch1
  1673. try:
  1674. revision1 = int(revision1)
  1675. except ValueError:
  1676. continue
  1677. branch_map[branch1] = revision1
  1678. return branch_map.get(branch0)
  1679. return None
  1680. def get_version(self, version_file=None, version_variable=None):
  1681. """Try to get version string of a package.
  1682. Return a version string of the current package or None if the version
  1683. information could not be detected.
  1684. Notes
  1685. -----
  1686. This method scans files named
  1687. __version__.py, <packagename>_version.py, version.py, and
  1688. __svn_version__.py for string variables version, __version__, and
  1689. <packagename>_version, until a version number is found.
  1690. """
  1691. version = getattr(self, 'version', None)
  1692. if version is not None:
  1693. return version
  1694. # Get version from version file.
  1695. if version_file is None:
  1696. files = ['__version__.py',
  1697. self.name.split('.')[-1]+'_version.py',
  1698. 'version.py',
  1699. '__svn_version__.py',
  1700. '__hg_version__.py']
  1701. else:
  1702. files = [version_file]
  1703. if version_variable is None:
  1704. version_vars = ['version',
  1705. '__version__',
  1706. self.name.split('.')[-1]+'_version']
  1707. else:
  1708. version_vars = [version_variable]
  1709. for f in files:
  1710. fn = njoin(self.local_path, f)
  1711. if os.path.isfile(fn):
  1712. info = ('.py', 'U', 1)
  1713. name = os.path.splitext(os.path.basename(fn))[0]
  1714. n = dot_join(self.name, name)
  1715. try:
  1716. version_module = exec_mod_from_location(
  1717. '_'.join(n.split('.')), fn)
  1718. except ImportError as e:
  1719. self.warn(str(e))
  1720. version_module = None
  1721. if version_module is None:
  1722. continue
  1723. for a in version_vars:
  1724. version = getattr(version_module, a, None)
  1725. if version is not None:
  1726. break
  1727. # Try if versioneer module
  1728. try:
  1729. version = version_module.get_versions()['version']
  1730. except AttributeError:
  1731. pass
  1732. if version is not None:
  1733. break
  1734. if version is not None:
  1735. self.version = version
  1736. return version
  1737. # Get version as SVN or Mercurial revision number
  1738. revision = self._get_svn_revision(self.local_path)
  1739. if revision is None:
  1740. revision = self._get_hg_revision(self.local_path)
  1741. if revision is not None:
  1742. version = str(revision)
  1743. self.version = version
  1744. return version
  1745. def make_svn_version_py(self, delete=True):
  1746. """Appends a data function to the data_files list that will generate
  1747. __svn_version__.py file to the current package directory.
  1748. Generate package __svn_version__.py file from SVN revision number,
  1749. it will be removed after python exits but will be available
  1750. when sdist, etc commands are executed.
  1751. Notes
  1752. -----
  1753. If __svn_version__.py existed before, nothing is done.
  1754. This is
  1755. intended for working with source directories that are in an SVN
  1756. repository.
  1757. """
  1758. target = njoin(self.local_path, '__svn_version__.py')
  1759. revision = self._get_svn_revision(self.local_path)
  1760. if os.path.isfile(target) or revision is None:
  1761. return
  1762. else:
  1763. def generate_svn_version_py():
  1764. if not os.path.isfile(target):
  1765. version = str(revision)
  1766. self.info('Creating %s (version=%r)' % (target, version))
  1767. with open(target, 'w') as f:
  1768. f.write('version = %r\n' % (version))
  1769. def rm_file(f=target,p=self.info):
  1770. if delete:
  1771. try: os.remove(f); p('removed '+f)
  1772. except OSError: pass
  1773. try: os.remove(f+'c'); p('removed '+f+'c')
  1774. except OSError: pass
  1775. atexit.register(rm_file)
  1776. return target
  1777. self.add_data_files(('', generate_svn_version_py()))
  1778. def make_hg_version_py(self, delete=True):
  1779. """Appends a data function to the data_files list that will generate
  1780. __hg_version__.py file to the current package directory.
  1781. Generate package __hg_version__.py file from Mercurial revision,
  1782. it will be removed after python exits but will be available
  1783. when sdist, etc commands are executed.
  1784. Notes
  1785. -----
  1786. If __hg_version__.py existed before, nothing is done.
  1787. This is intended for working with source directories that are
  1788. in an Mercurial repository.
  1789. """
  1790. target = njoin(self.local_path, '__hg_version__.py')
  1791. revision = self._get_hg_revision(self.local_path)
  1792. if os.path.isfile(target) or revision is None:
  1793. return
  1794. else:
  1795. def generate_hg_version_py():
  1796. if not os.path.isfile(target):
  1797. version = str(revision)
  1798. self.info('Creating %s (version=%r)' % (target, version))
  1799. with open(target, 'w') as f:
  1800. f.write('version = %r\n' % (version))
  1801. def rm_file(f=target,p=self.info):
  1802. if delete:
  1803. try: os.remove(f); p('removed '+f)
  1804. except OSError: pass
  1805. try: os.remove(f+'c'); p('removed '+f+'c')
  1806. except OSError: pass
  1807. atexit.register(rm_file)
  1808. return target
  1809. self.add_data_files(('', generate_hg_version_py()))
  1810. def make_config_py(self,name='__config__'):
  1811. """Generate package __config__.py file containing system_info
  1812. information used during building the package.
  1813. This file is installed to the
  1814. package installation directory.
  1815. """
  1816. self.py_modules.append((self.name, name, generate_config_py))
  1817. def get_info(self,*names):
  1818. """Get resources information.
  1819. Return information (from system_info.get_info) for all of the names in
  1820. the argument list in a single dictionary.
  1821. """
  1822. from .system_info import get_info, dict_append
  1823. info_dict = {}
  1824. for a in names:
  1825. dict_append(info_dict,**get_info(a))
  1826. return info_dict
  1827. def get_cmd(cmdname, _cache={}):
  1828. if cmdname not in _cache:
  1829. import distutils.core
  1830. dist = distutils.core._setup_distribution
  1831. if dist is None:
  1832. from distutils.errors import DistutilsInternalError
  1833. raise DistutilsInternalError(
  1834. 'setup distribution instance not initialized')
  1835. cmd = dist.get_command_obj(cmdname)
  1836. _cache[cmdname] = cmd
  1837. return _cache[cmdname]
  1838. def get_numpy_include_dirs():
  1839. # numpy_include_dirs are set by numpy/core/setup.py, otherwise []
  1840. include_dirs = Configuration.numpy_include_dirs[:]
  1841. if not include_dirs:
  1842. import numpy
  1843. include_dirs = [ numpy.get_include() ]
  1844. # else running numpy/core/setup.py
  1845. return include_dirs
  1846. def get_npy_pkg_dir():
  1847. """Return the path where to find the npy-pkg-config directory.
  1848. If the NPY_PKG_CONFIG_PATH environment variable is set, the value of that
  1849. is returned. Otherwise, a path inside the location of the numpy module is
  1850. returned.
  1851. The NPY_PKG_CONFIG_PATH can be useful when cross-compiling, maintaining
  1852. customized npy-pkg-config .ini files for the cross-compilation
  1853. environment, and using them when cross-compiling.
  1854. """
  1855. d = os.environ.get('NPY_PKG_CONFIG_PATH')
  1856. if d is not None:
  1857. return d
  1858. spec = importlib.util.find_spec('numpy')
  1859. d = os.path.join(os.path.dirname(spec.origin),
  1860. 'core', 'lib', 'npy-pkg-config')
  1861. return d
  1862. def get_pkg_info(pkgname, dirs=None):
  1863. """
  1864. Return library info for the given package.
  1865. Parameters
  1866. ----------
  1867. pkgname : str
  1868. Name of the package (should match the name of the .ini file, without
  1869. the extension, e.g. foo for the file foo.ini).
  1870. dirs : sequence, optional
  1871. If given, should be a sequence of additional directories where to look
  1872. for npy-pkg-config files. Those directories are searched prior to the
  1873. NumPy directory.
  1874. Returns
  1875. -------
  1876. pkginfo : class instance
  1877. The `LibraryInfo` instance containing the build information.
  1878. Raises
  1879. ------
  1880. PkgNotFound
  1881. If the package is not found.
  1882. See Also
  1883. --------
  1884. Configuration.add_npy_pkg_config, Configuration.add_installed_library,
  1885. get_info
  1886. """
  1887. from numpy.distutils.npy_pkg_config import read_config
  1888. if dirs:
  1889. dirs.append(get_npy_pkg_dir())
  1890. else:
  1891. dirs = [get_npy_pkg_dir()]
  1892. return read_config(pkgname, dirs)
  1893. def get_info(pkgname, dirs=None):
  1894. """
  1895. Return an info dict for a given C library.
  1896. The info dict contains the necessary options to use the C library.
  1897. Parameters
  1898. ----------
  1899. pkgname : str
  1900. Name of the package (should match the name of the .ini file, without
  1901. the extension, e.g. foo for the file foo.ini).
  1902. dirs : sequence, optional
  1903. If given, should be a sequence of additional directories where to look
  1904. for npy-pkg-config files. Those directories are searched prior to the
  1905. NumPy directory.
  1906. Returns
  1907. -------
  1908. info : dict
  1909. The dictionary with build information.
  1910. Raises
  1911. ------
  1912. PkgNotFound
  1913. If the package is not found.
  1914. See Also
  1915. --------
  1916. Configuration.add_npy_pkg_config, Configuration.add_installed_library,
  1917. get_pkg_info
  1918. Examples
  1919. --------
  1920. To get the necessary information for the npymath library from NumPy:
  1921. >>> npymath_info = np.distutils.misc_util.get_info('npymath')
  1922. >>> npymath_info #doctest: +SKIP
  1923. {'define_macros': [], 'libraries': ['npymath'], 'library_dirs':
  1924. ['.../numpy/core/lib'], 'include_dirs': ['.../numpy/core/include']}
  1925. This info dict can then be used as input to a `Configuration` instance::
  1926. config.add_extension('foo', sources=['foo.c'], extra_info=npymath_info)
  1927. """
  1928. from numpy.distutils.npy_pkg_config import parse_flags
  1929. pkg_info = get_pkg_info(pkgname, dirs)
  1930. # Translate LibraryInfo instance into a build_info dict
  1931. info = parse_flags(pkg_info.cflags())
  1932. for k, v in parse_flags(pkg_info.libs()).items():
  1933. info[k].extend(v)
  1934. # add_extension extra_info argument is ANAL
  1935. info['define_macros'] = info['macros']
  1936. del info['macros']
  1937. del info['ignored']
  1938. return info
  1939. def is_bootstrapping():
  1940. import builtins
  1941. try:
  1942. builtins.__NUMPY_SETUP__
  1943. return True
  1944. except AttributeError:
  1945. return False
  1946. #########################
  1947. def default_config_dict(name = None, parent_name = None, local_path=None):
  1948. """Return a configuration dictionary for usage in
  1949. configuration() function defined in file setup_<name>.py.
  1950. """
  1951. import warnings
  1952. warnings.warn('Use Configuration(%r,%r,top_path=%r) instead of '\
  1953. 'deprecated default_config_dict(%r,%r,%r)'
  1954. % (name, parent_name, local_path,
  1955. name, parent_name, local_path,
  1956. ), stacklevel=2)
  1957. c = Configuration(name, parent_name, local_path)
  1958. return c.todict()
  1959. def dict_append(d, **kws):
  1960. for k, v in kws.items():
  1961. if k in d:
  1962. ov = d[k]
  1963. if isinstance(ov, str):
  1964. d[k] = v
  1965. else:
  1966. d[k].extend(v)
  1967. else:
  1968. d[k] = v
  1969. def appendpath(prefix, path):
  1970. if os.path.sep != '/':
  1971. prefix = prefix.replace('/', os.path.sep)
  1972. path = path.replace('/', os.path.sep)
  1973. drive = ''
  1974. if os.path.isabs(path):
  1975. drive = os.path.splitdrive(prefix)[0]
  1976. absprefix = os.path.splitdrive(os.path.abspath(prefix))[1]
  1977. pathdrive, path = os.path.splitdrive(path)
  1978. d = os.path.commonprefix([absprefix, path])
  1979. if os.path.join(absprefix[:len(d)], absprefix[len(d):]) != absprefix \
  1980. or os.path.join(path[:len(d)], path[len(d):]) != path:
  1981. # Handle invalid paths
  1982. d = os.path.dirname(d)
  1983. subpath = path[len(d):]
  1984. if os.path.isabs(subpath):
  1985. subpath = subpath[1:]
  1986. else:
  1987. subpath = path
  1988. return os.path.normpath(njoin(drive + prefix, subpath))
  1989. def generate_config_py(target):
  1990. """Generate config.py file containing system_info information
  1991. used during building the package.
  1992. Usage:
  1993. config['py_modules'].append((packagename, '__config__',generate_config_py))
  1994. """
  1995. from numpy.distutils.system_info import system_info
  1996. from distutils.dir_util import mkpath
  1997. mkpath(os.path.dirname(target))
  1998. with open(target, 'w') as f:
  1999. f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0])))
  2000. f.write('# It contains system_info results at the time of building this package.\n')
  2001. f.write('__all__ = ["get_info","show"]\n\n')
  2002. # For gfortran+msvc combination, extra shared libraries may exist
  2003. f.write(textwrap.dedent("""
  2004. import os
  2005. import sys
  2006. extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
  2007. if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
  2008. if sys.version_info >= (3, 8):
  2009. os.add_dll_directory(extra_dll_dir)
  2010. else:
  2011. os.environ.setdefault('PATH', '')
  2012. os.environ['PATH'] += os.pathsep + extra_dll_dir
  2013. """))
  2014. for k, i in system_info.saved_results.items():
  2015. f.write('%s=%r\n' % (k, i))
  2016. f.write(textwrap.dedent(r'''
  2017. def get_info(name):
  2018. g = globals()
  2019. return g.get(name, g.get(name + "_info", {}))
  2020. def show():
  2021. """
  2022. Show libraries in the system on which NumPy was built.
  2023. Print information about various resources (libraries, library
  2024. directories, include directories, etc.) in the system on which
  2025. NumPy was built.
  2026. See Also
  2027. --------
  2028. get_include : Returns the directory containing NumPy C
  2029. header files.
  2030. Notes
  2031. -----
  2032. Classes specifying the information to be printed are defined
  2033. in the `numpy.distutils.system_info` module.
  2034. Information may include:
  2035. * ``language``: language used to write the libraries (mostly
  2036. C or f77)
  2037. * ``libraries``: names of libraries found in the system
  2038. * ``library_dirs``: directories containing the libraries
  2039. * ``include_dirs``: directories containing library header files
  2040. * ``src_dirs``: directories containing library source files
  2041. * ``define_macros``: preprocessor macros used by
  2042. ``distutils.setup``
  2043. * ``baseline``: minimum CPU features required
  2044. * ``found``: dispatched features supported in the system
  2045. * ``not found``: dispatched features that are not supported
  2046. in the system
  2047. Examples
  2048. --------
  2049. >>> import numpy as np
  2050. >>> np.show_config()
  2051. blas_opt_info:
  2052. language = c
  2053. define_macros = [('HAVE_CBLAS', None)]
  2054. libraries = ['openblas', 'openblas']
  2055. library_dirs = ['/usr/local/lib']
  2056. """
  2057. from numpy.core._multiarray_umath import (
  2058. __cpu_features__, __cpu_baseline__, __cpu_dispatch__
  2059. )
  2060. for name,info_dict in globals().items():
  2061. if name[0] == "_" or type(info_dict) is not type({}): continue
  2062. print(name + ":")
  2063. if not info_dict:
  2064. print(" NOT AVAILABLE")
  2065. for k,v in info_dict.items():
  2066. v = str(v)
  2067. if k == "sources" and len(v) > 200:
  2068. v = v[:60] + " ...\n... " + v[-60:]
  2069. print(" %s = %s" % (k,v))
  2070. features_found, features_not_found = [], []
  2071. for feature in __cpu_dispatch__:
  2072. if __cpu_features__[feature]:
  2073. features_found.append(feature)
  2074. else:
  2075. features_not_found.append(feature)
  2076. print("Supported SIMD extensions in this NumPy install:")
  2077. print(" baseline = %s" % (','.join(__cpu_baseline__)))
  2078. print(" found = %s" % (','.join(features_found)))
  2079. print(" not found = %s" % (','.join(features_not_found)))
  2080. '''))
  2081. return target
  2082. def msvc_version(compiler):
  2083. """Return version major and minor of compiler instance if it is
  2084. MSVC, raise an exception otherwise."""
  2085. if not compiler.compiler_type == "msvc":
  2086. raise ValueError("Compiler instance is not msvc (%s)"\
  2087. % compiler.compiler_type)
  2088. return compiler._MSVCCompiler__version
  2089. def get_build_architecture():
  2090. # Importing distutils.msvccompiler triggers a warning on non-Windows
  2091. # systems, so delay the import to here.
  2092. from distutils.msvccompiler import get_build_architecture
  2093. return get_build_architecture()
  2094. _cxx_ignore_flags = {'-Werror=implicit-function-declaration', '-std=c99'}
  2095. def sanitize_cxx_flags(cxxflags):
  2096. '''
  2097. Some flags are valid for C but not C++. Prune them.
  2098. '''
  2099. return [flag for flag in cxxflags if flag not in _cxx_ignore_flags]
  2100. def exec_mod_from_location(modname, modfile):
  2101. '''
  2102. Use importlib machinery to import a module `modname` from the file
  2103. `modfile`. Depending on the `spec.loader`, the module may not be
  2104. registered in sys.modules.
  2105. '''
  2106. spec = importlib.util.spec_from_file_location(modname, modfile)
  2107. foo = importlib.util.module_from_spec(spec)
  2108. spec.loader.exec_module(foo)
  2109. return foo