f2py2e.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. #!/usr/bin/env python3
  2. """
  3. f2py2e - Fortran to Python C/API generator. 2nd Edition.
  4. See __usage__ below.
  5. Copyright 1999--2011 Pearu Peterson all rights reserved,
  6. Pearu Peterson <pearu@cens.ioc.ee>
  7. Permission to use, modify, and distribute this software is given under the
  8. terms of the NumPy License.
  9. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
  10. $Date: 2005/05/06 08:31:19 $
  11. Pearu Peterson
  12. """
  13. import sys
  14. import os
  15. import pprint
  16. import re
  17. from pathlib import Path
  18. from . import crackfortran
  19. from . import rules
  20. from . import cb_rules
  21. from . import auxfuncs
  22. from . import cfuncs
  23. from . import f90mod_rules
  24. from . import __version__
  25. from . import capi_maps
  26. f2py_version = __version__.version
  27. numpy_version = __version__.version
  28. errmess = sys.stderr.write
  29. # outmess=sys.stdout.write
  30. show = pprint.pprint
  31. outmess = auxfuncs.outmess
  32. __usage__ =\
  33. f"""Usage:
  34. 1) To construct extension module sources:
  35. f2py [<options>] <fortran files> [[[only:]||[skip:]] \\
  36. <fortran functions> ] \\
  37. [: <fortran files> ...]
  38. 2) To compile fortran files and build extension modules:
  39. f2py -c [<options>, <build_flib options>, <extra options>] <fortran files>
  40. 3) To generate signature files:
  41. f2py -h <filename.pyf> ...< same options as in (1) >
  42. Description: This program generates a Python C/API file (<modulename>module.c)
  43. that contains wrappers for given fortran functions so that they
  44. can be called from Python. With the -c option the corresponding
  45. extension modules are built.
  46. Options:
  47. --2d-numpy Use numpy.f2py tool with NumPy support. [DEFAULT]
  48. --2d-numeric Use f2py2e tool with Numeric support.
  49. --2d-numarray Use f2py2e tool with Numarray support.
  50. --g3-numpy Use 3rd generation f2py from the separate f2py package.
  51. [NOT AVAILABLE YET]
  52. -h <filename> Write signatures of the fortran routines to file <filename>
  53. and exit. You can then edit <filename> and use it instead
  54. of <fortran files>. If <filename>==stdout then the
  55. signatures are printed to stdout.
  56. <fortran functions> Names of fortran routines for which Python C/API
  57. functions will be generated. Default is all that are found
  58. in <fortran files>.
  59. <fortran files> Paths to fortran/signature files that will be scanned for
  60. <fortran functions> in order to determine their signatures.
  61. skip: Ignore fortran functions that follow until `:'.
  62. only: Use only fortran functions that follow until `:'.
  63. : Get back to <fortran files> mode.
  64. -m <modulename> Name of the module; f2py generates a Python/C API
  65. file <modulename>module.c or extension module <modulename>.
  66. Default is 'untitled'.
  67. '-include<header>' Writes additional headers in the C wrapper, can be passed
  68. multiple times, generates #include <header> each time.
  69. --[no-]lower Do [not] lower the cases in <fortran files>. By default,
  70. --lower is assumed with -h key, and --no-lower without -h key.
  71. --build-dir <dirname> All f2py generated files are created in <dirname>.
  72. Default is tempfile.mkdtemp().
  73. --overwrite-signature Overwrite existing signature file.
  74. --[no-]latex-doc Create (or not) <modulename>module.tex.
  75. Default is --no-latex-doc.
  76. --short-latex Create 'incomplete' LaTeX document (without commands
  77. \\documentclass, \\tableofcontents, and \\begin{{document}},
  78. \\end{{document}}).
  79. --[no-]rest-doc Create (or not) <modulename>module.rst.
  80. Default is --no-rest-doc.
  81. --debug-capi Create C/API code that reports the state of the wrappers
  82. during runtime. Useful for debugging.
  83. --[no-]wrap-functions Create Fortran subroutine wrappers to Fortran 77
  84. functions. --wrap-functions is default because it ensures
  85. maximum portability/compiler independence.
  86. --include-paths <path1>:<path2>:... Search include files from the given
  87. directories.
  88. --help-link [..] List system resources found by system_info.py. See also
  89. --link-<resource> switch below. [..] is optional list
  90. of resources names. E.g. try 'f2py --help-link lapack_opt'.
  91. --f2cmap <filename> Load Fortran-to-Python KIND specification from the given
  92. file. Default: .f2py_f2cmap in current directory.
  93. --quiet Run quietly.
  94. --verbose Run with extra verbosity.
  95. --skip-empty-wrappers Only generate wrapper files when needed.
  96. -v Print f2py version ID and exit.
  97. numpy.distutils options (only effective with -c):
  98. --fcompiler= Specify Fortran compiler type by vendor
  99. --compiler= Specify C compiler type (as defined by distutils)
  100. --help-fcompiler List available Fortran compilers and exit
  101. --f77exec= Specify the path to F77 compiler
  102. --f90exec= Specify the path to F90 compiler
  103. --f77flags= Specify F77 compiler flags
  104. --f90flags= Specify F90 compiler flags
  105. --opt= Specify optimization flags
  106. --arch= Specify architecture specific optimization flags
  107. --noopt Compile without optimization
  108. --noarch Compile without arch-dependent optimization
  109. --debug Compile with debugging information
  110. Extra options (only effective with -c):
  111. --link-<resource> Link extension module with <resource> as defined
  112. by numpy.distutils/system_info.py. E.g. to link
  113. with optimized LAPACK libraries (vecLib on MacOSX,
  114. ATLAS elsewhere), use --link-lapack_opt.
  115. See also --help-link switch.
  116. -L/path/to/lib/ -l<libname>
  117. -D<define> -U<name>
  118. -I/path/to/include/
  119. <filename>.o <filename>.so <filename>.a
  120. Using the following macros may be required with non-gcc Fortran
  121. compilers:
  122. -DPREPEND_FORTRAN -DNO_APPEND_FORTRAN -DUPPERCASE_FORTRAN
  123. -DUNDERSCORE_G77
  124. When using -DF2PY_REPORT_ATEXIT, a performance report of F2PY
  125. interface is printed out at exit (platforms: Linux).
  126. When using -DF2PY_REPORT_ON_ARRAY_COPY=<int>, a message is
  127. sent to stderr whenever F2PY interface makes a copy of an
  128. array. Integer <int> sets the threshold for array sizes when
  129. a message should be shown.
  130. Version: {f2py_version}
  131. numpy Version: {numpy_version}
  132. Requires: Python 3.5 or higher.
  133. License: NumPy license (see LICENSE.txt in the NumPy source code)
  134. Copyright 1999 - 2011 Pearu Peterson all rights reserved.
  135. https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e"""
  136. def scaninputline(inputline):
  137. files, skipfuncs, onlyfuncs, debug = [], [], [], []
  138. f, f2, f3, f5, f6, f7, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0, 0
  139. verbose = 1
  140. emptygen = True
  141. dolc = -1
  142. dolatexdoc = 0
  143. dorestdoc = 0
  144. wrapfuncs = 1
  145. buildpath = '.'
  146. include_paths = []
  147. signsfile, modulename = None, None
  148. options = {'buildpath': buildpath,
  149. 'coutput': None,
  150. 'f2py_wrapper_output': None}
  151. for l in inputline:
  152. if l == '':
  153. pass
  154. elif l == 'only:':
  155. f = 0
  156. elif l == 'skip:':
  157. f = -1
  158. elif l == ':':
  159. f = 1
  160. elif l[:8] == '--debug-':
  161. debug.append(l[8:])
  162. elif l == '--lower':
  163. dolc = 1
  164. elif l == '--build-dir':
  165. f6 = 1
  166. elif l == '--no-lower':
  167. dolc = 0
  168. elif l == '--quiet':
  169. verbose = 0
  170. elif l == '--verbose':
  171. verbose += 1
  172. elif l == '--latex-doc':
  173. dolatexdoc = 1
  174. elif l == '--no-latex-doc':
  175. dolatexdoc = 0
  176. elif l == '--rest-doc':
  177. dorestdoc = 1
  178. elif l == '--no-rest-doc':
  179. dorestdoc = 0
  180. elif l == '--wrap-functions':
  181. wrapfuncs = 1
  182. elif l == '--no-wrap-functions':
  183. wrapfuncs = 0
  184. elif l == '--short-latex':
  185. options['shortlatex'] = 1
  186. elif l == '--coutput':
  187. f8 = 1
  188. elif l == '--f2py-wrapper-output':
  189. f9 = 1
  190. elif l == '--f2cmap':
  191. f10 = 1
  192. elif l == '--overwrite-signature':
  193. options['h-overwrite'] = 1
  194. elif l == '-h':
  195. f2 = 1
  196. elif l == '-m':
  197. f3 = 1
  198. elif l[:2] == '-v':
  199. print(f2py_version)
  200. sys.exit()
  201. elif l == '--show-compilers':
  202. f5 = 1
  203. elif l[:8] == '-include':
  204. cfuncs.outneeds['userincludes'].append(l[9:-1])
  205. cfuncs.userincludes[l[9:-1]] = '#include ' + l[8:]
  206. elif l[:15] in '--include_paths':
  207. outmess(
  208. 'f2py option --include_paths is deprecated, use --include-paths instead.\n')
  209. f7 = 1
  210. elif l[:15] in '--include-paths':
  211. f7 = 1
  212. elif l == '--skip-empty-wrappers':
  213. emptygen = False
  214. elif l[0] == '-':
  215. errmess('Unknown option %s\n' % repr(l))
  216. sys.exit()
  217. elif f2:
  218. f2 = 0
  219. signsfile = l
  220. elif f3:
  221. f3 = 0
  222. modulename = l
  223. elif f6:
  224. f6 = 0
  225. buildpath = l
  226. elif f7:
  227. f7 = 0
  228. include_paths.extend(l.split(os.pathsep))
  229. elif f8:
  230. f8 = 0
  231. options["coutput"] = l
  232. elif f9:
  233. f9 = 0
  234. options["f2py_wrapper_output"] = l
  235. elif f10:
  236. f10 = 0
  237. options["f2cmap_file"] = l
  238. elif f == 1:
  239. try:
  240. with open(l):
  241. pass
  242. files.append(l)
  243. except OSError as detail:
  244. errmess(f'OSError: {detail!s}. Skipping file "{l!s}".\n')
  245. elif f == -1:
  246. skipfuncs.append(l)
  247. elif f == 0:
  248. onlyfuncs.append(l)
  249. if not f5 and not files and not modulename:
  250. print(__usage__)
  251. sys.exit()
  252. if not os.path.isdir(buildpath):
  253. if not verbose:
  254. outmess('Creating build directory %s\n' % (buildpath))
  255. os.mkdir(buildpath)
  256. if signsfile:
  257. signsfile = os.path.join(buildpath, signsfile)
  258. if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options:
  259. errmess(
  260. 'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile))
  261. sys.exit()
  262. options['emptygen'] = emptygen
  263. options['debug'] = debug
  264. options['verbose'] = verbose
  265. if dolc == -1 and not signsfile:
  266. options['do-lower'] = 0
  267. else:
  268. options['do-lower'] = dolc
  269. if modulename:
  270. options['module'] = modulename
  271. if signsfile:
  272. options['signsfile'] = signsfile
  273. if onlyfuncs:
  274. options['onlyfuncs'] = onlyfuncs
  275. if skipfuncs:
  276. options['skipfuncs'] = skipfuncs
  277. options['dolatexdoc'] = dolatexdoc
  278. options['dorestdoc'] = dorestdoc
  279. options['wrapfuncs'] = wrapfuncs
  280. options['buildpath'] = buildpath
  281. options['include_paths'] = include_paths
  282. options.setdefault('f2cmap_file', None)
  283. return files, options
  284. def callcrackfortran(files, options):
  285. rules.options = options
  286. crackfortran.debug = options['debug']
  287. crackfortran.verbose = options['verbose']
  288. if 'module' in options:
  289. crackfortran.f77modulename = options['module']
  290. if 'skipfuncs' in options:
  291. crackfortran.skipfuncs = options['skipfuncs']
  292. if 'onlyfuncs' in options:
  293. crackfortran.onlyfuncs = options['onlyfuncs']
  294. crackfortran.include_paths[:] = options['include_paths']
  295. crackfortran.dolowercase = options['do-lower']
  296. postlist = crackfortran.crackfortran(files)
  297. if 'signsfile' in options:
  298. outmess('Saving signatures to file "%s"\n' % (options['signsfile']))
  299. pyf = crackfortran.crack2fortran(postlist)
  300. if options['signsfile'][-6:] == 'stdout':
  301. sys.stdout.write(pyf)
  302. else:
  303. with open(options['signsfile'], 'w') as f:
  304. f.write(pyf)
  305. if options["coutput"] is None:
  306. for mod in postlist:
  307. mod["coutput"] = "%smodule.c" % mod["name"]
  308. else:
  309. for mod in postlist:
  310. mod["coutput"] = options["coutput"]
  311. if options["f2py_wrapper_output"] is None:
  312. for mod in postlist:
  313. mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"]
  314. else:
  315. for mod in postlist:
  316. mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]
  317. return postlist
  318. def buildmodules(lst):
  319. cfuncs.buildcfuncs()
  320. outmess('Building modules...\n')
  321. modules, mnames, isusedby = [], [], {}
  322. for item in lst:
  323. if '__user__' in item['name']:
  324. cb_rules.buildcallbacks(item)
  325. else:
  326. if 'use' in item:
  327. for u in item['use'].keys():
  328. if u not in isusedby:
  329. isusedby[u] = []
  330. isusedby[u].append(item['name'])
  331. modules.append(item)
  332. mnames.append(item['name'])
  333. ret = {}
  334. for module, name in zip(modules, mnames):
  335. if name in isusedby:
  336. outmess('\tSkipping module "%s" which is used by %s.\n' % (
  337. name, ','.join('"%s"' % s for s in isusedby[name])))
  338. else:
  339. um = []
  340. if 'use' in module:
  341. for u in module['use'].keys():
  342. if u in isusedby and u in mnames:
  343. um.append(modules[mnames.index(u)])
  344. else:
  345. outmess(
  346. f'\tModule "{name}" uses nonexisting "{u}" '
  347. 'which will be ignored.\n')
  348. ret[name] = {}
  349. dict_append(ret[name], rules.buildmodule(module, um))
  350. return ret
  351. def dict_append(d_out, d_in):
  352. for (k, v) in d_in.items():
  353. if k not in d_out:
  354. d_out[k] = []
  355. if isinstance(v, list):
  356. d_out[k] = d_out[k] + v
  357. else:
  358. d_out[k].append(v)
  359. def run_main(comline_list):
  360. """
  361. Equivalent to running::
  362. f2py <args>
  363. where ``<args>=string.join(<list>,' ')``, but in Python. Unless
  364. ``-h`` is used, this function returns a dictionary containing
  365. information on generated modules and their dependencies on source
  366. files.
  367. You cannot build extension modules with this function, that is,
  368. using ``-c`` is not allowed. Use the ``compile`` command instead.
  369. Examples
  370. --------
  371. The command ``f2py -m scalar scalar.f`` can be executed from Python as
  372. follows.
  373. .. literalinclude:: ../../source/f2py/code/results/run_main_session.dat
  374. :language: python
  375. """
  376. crackfortran.reset_global_f2py_vars()
  377. f2pydir = os.path.dirname(os.path.abspath(cfuncs.__file__))
  378. fobjhsrc = os.path.join(f2pydir, 'src', 'fortranobject.h')
  379. fobjcsrc = os.path.join(f2pydir, 'src', 'fortranobject.c')
  380. files, options = scaninputline(comline_list)
  381. auxfuncs.options = options
  382. capi_maps.load_f2cmap_file(options['f2cmap_file'])
  383. postlist = callcrackfortran(files, options)
  384. isusedby = {}
  385. for plist in postlist:
  386. if 'use' in plist:
  387. for u in plist['use'].keys():
  388. if u not in isusedby:
  389. isusedby[u] = []
  390. isusedby[u].append(plist['name'])
  391. for plist in postlist:
  392. if plist['block'] == 'python module' and '__user__' in plist['name']:
  393. if plist['name'] in isusedby:
  394. # if not quiet:
  395. outmess(
  396. f'Skipping Makefile build for module "{plist["name"]}" '
  397. 'which is used by {}\n'.format(
  398. ','.join(f'"{s}"' for s in isusedby[plist['name']])))
  399. if 'signsfile' in options:
  400. if options['verbose'] > 1:
  401. outmess(
  402. 'Stopping. Edit the signature file and then run f2py on the signature file: ')
  403. outmess('%s %s\n' %
  404. (os.path.basename(sys.argv[0]), options['signsfile']))
  405. return
  406. for plist in postlist:
  407. if plist['block'] != 'python module':
  408. if 'python module' not in options:
  409. errmess(
  410. 'Tip: If your original code is Fortran source then you must use -m option.\n')
  411. raise TypeError('All blocks must be python module blocks but got %s' % (
  412. repr(plist['block'])))
  413. auxfuncs.debugoptions = options['debug']
  414. f90mod_rules.options = options
  415. auxfuncs.wrapfuncs = options['wrapfuncs']
  416. ret = buildmodules(postlist)
  417. for mn in ret.keys():
  418. dict_append(ret[mn], {'csrc': fobjcsrc, 'h': fobjhsrc})
  419. return ret
  420. def filter_files(prefix, suffix, files, remove_prefix=None):
  421. """
  422. Filter files by prefix and suffix.
  423. """
  424. filtered, rest = [], []
  425. match = re.compile(prefix + r'.*' + suffix + r'\Z').match
  426. if remove_prefix:
  427. ind = len(prefix)
  428. else:
  429. ind = 0
  430. for file in [x.strip() for x in files]:
  431. if match(file):
  432. filtered.append(file[ind:])
  433. else:
  434. rest.append(file)
  435. return filtered, rest
  436. def get_prefix(module):
  437. p = os.path.dirname(os.path.dirname(module.__file__))
  438. return p
  439. def run_compile():
  440. """
  441. Do it all in one call!
  442. """
  443. import tempfile
  444. i = sys.argv.index('-c')
  445. del sys.argv[i]
  446. remove_build_dir = 0
  447. try:
  448. i = sys.argv.index('--build-dir')
  449. except ValueError:
  450. i = None
  451. if i is not None:
  452. build_dir = sys.argv[i + 1]
  453. del sys.argv[i + 1]
  454. del sys.argv[i]
  455. else:
  456. remove_build_dir = 1
  457. build_dir = tempfile.mkdtemp()
  458. _reg1 = re.compile(r'--link-')
  459. sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)]
  460. sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags]
  461. if sysinfo_flags:
  462. sysinfo_flags = [f[7:] for f in sysinfo_flags]
  463. _reg2 = re.compile(
  464. r'--((no-|)(wrap-functions|lower)|debug-capi|quiet|skip-empty-wrappers)|-include')
  465. f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)]
  466. sys.argv = [_m for _m in sys.argv if _m not in f2py_flags]
  467. f2py_flags2 = []
  468. fl = 0
  469. for a in sys.argv[1:]:
  470. if a in ['only:', 'skip:']:
  471. fl = 1
  472. elif a == ':':
  473. fl = 0
  474. if fl or a == ':':
  475. f2py_flags2.append(a)
  476. if f2py_flags2 and f2py_flags2[-1] != ':':
  477. f2py_flags2.append(':')
  478. f2py_flags.extend(f2py_flags2)
  479. sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2]
  480. _reg3 = re.compile(
  481. r'--((f(90)?compiler(-exec|)|compiler)=|help-compiler)')
  482. flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)]
  483. sys.argv = [_m for _m in sys.argv if _m not in flib_flags]
  484. _reg4 = re.compile(
  485. r'--((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help-fcompiler))')
  486. fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)]
  487. sys.argv = [_m for _m in sys.argv if _m not in fc_flags]
  488. del_list = []
  489. for s in flib_flags:
  490. v = '--fcompiler='
  491. if s[:len(v)] == v:
  492. from numpy.distutils import fcompiler
  493. fcompiler.load_all_fcompiler_classes()
  494. allowed_keys = list(fcompiler.fcompiler_class.keys())
  495. nv = ov = s[len(v):].lower()
  496. if ov not in allowed_keys:
  497. vmap = {} # XXX
  498. try:
  499. nv = vmap[ov]
  500. except KeyError:
  501. if ov not in vmap.values():
  502. print('Unknown vendor: "%s"' % (s[len(v):]))
  503. nv = ov
  504. i = flib_flags.index(s)
  505. flib_flags[i] = '--fcompiler=' + nv
  506. continue
  507. for s in del_list:
  508. i = flib_flags.index(s)
  509. del flib_flags[i]
  510. assert len(flib_flags) <= 2, repr(flib_flags)
  511. _reg5 = re.compile(r'--(verbose)')
  512. setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]
  513. sys.argv = [_m for _m in sys.argv if _m not in setup_flags]
  514. if '--quiet' in f2py_flags:
  515. setup_flags.append('--quiet')
  516. modulename = 'untitled'
  517. sources = sys.argv[1:]
  518. for optname in ['--include_paths', '--include-paths', '--f2cmap']:
  519. if optname in sys.argv:
  520. i = sys.argv.index(optname)
  521. f2py_flags.extend(sys.argv[i:i + 2])
  522. del sys.argv[i + 1], sys.argv[i]
  523. sources = sys.argv[1:]
  524. if '-m' in sys.argv:
  525. i = sys.argv.index('-m')
  526. modulename = sys.argv[i + 1]
  527. del sys.argv[i + 1], sys.argv[i]
  528. sources = sys.argv[1:]
  529. else:
  530. from numpy.distutils.command.build_src import get_f2py_modulename
  531. pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources)
  532. sources = pyf_files + sources
  533. for f in pyf_files:
  534. modulename = get_f2py_modulename(f)
  535. if modulename:
  536. break
  537. extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources)
  538. include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1)
  539. library_dirs, sources = filter_files('-L', '', sources, remove_prefix=1)
  540. libraries, sources = filter_files('-l', '', sources, remove_prefix=1)
  541. undef_macros, sources = filter_files('-U', '', sources, remove_prefix=1)
  542. define_macros, sources = filter_files('-D', '', sources, remove_prefix=1)
  543. for i in range(len(define_macros)):
  544. name_value = define_macros[i].split('=', 1)
  545. if len(name_value) == 1:
  546. name_value.append(None)
  547. if len(name_value) == 2:
  548. define_macros[i] = tuple(name_value)
  549. else:
  550. print('Invalid use of -D:', name_value)
  551. from numpy.distutils.system_info import get_info
  552. num_info = {}
  553. if num_info:
  554. include_dirs.extend(num_info.get('include_dirs', []))
  555. from numpy.distutils.core import setup, Extension
  556. ext_args = {'name': modulename, 'sources': sources,
  557. 'include_dirs': include_dirs,
  558. 'library_dirs': library_dirs,
  559. 'libraries': libraries,
  560. 'define_macros': define_macros,
  561. 'undef_macros': undef_macros,
  562. 'extra_objects': extra_objects,
  563. 'f2py_options': f2py_flags,
  564. }
  565. if sysinfo_flags:
  566. from numpy.distutils.misc_util import dict_append
  567. for n in sysinfo_flags:
  568. i = get_info(n)
  569. if not i:
  570. outmess('No %s resources found in system'
  571. ' (try `f2py --help-link`)\n' % (repr(n)))
  572. dict_append(ext_args, **i)
  573. ext = Extension(**ext_args)
  574. sys.argv = [sys.argv[0]] + setup_flags
  575. sys.argv.extend(['build',
  576. '--build-temp', build_dir,
  577. '--build-base', build_dir,
  578. '--build-platlib', '.',
  579. # disable CCompilerOpt
  580. '--disable-optimization'])
  581. if fc_flags:
  582. sys.argv.extend(['config_fc'] + fc_flags)
  583. if flib_flags:
  584. sys.argv.extend(['build_ext'] + flib_flags)
  585. setup(ext_modules=[ext])
  586. if remove_build_dir and os.path.exists(build_dir):
  587. import shutil
  588. outmess('Removing build directory %s\n' % (build_dir))
  589. shutil.rmtree(build_dir)
  590. def main():
  591. if '--help-link' in sys.argv[1:]:
  592. sys.argv.remove('--help-link')
  593. from numpy.distutils.system_info import show_all
  594. show_all()
  595. return
  596. # Probably outdated options that were not working before 1.16
  597. if '--g3-numpy' in sys.argv[1:]:
  598. sys.stderr.write("G3 f2py support is not implemented, yet.\\n")
  599. sys.exit(1)
  600. elif '--2e-numeric' in sys.argv[1:]:
  601. sys.argv.remove('--2e-numeric')
  602. elif '--2e-numarray' in sys.argv[1:]:
  603. # Note that this errors becaust the -DNUMARRAY argument is
  604. # not recognized. Just here for back compatibility and the
  605. # error message.
  606. sys.argv.append("-DNUMARRAY")
  607. sys.argv.remove('--2e-numarray')
  608. elif '--2e-numpy' in sys.argv[1:]:
  609. sys.argv.remove('--2e-numpy')
  610. else:
  611. pass
  612. if '-c' in sys.argv[1:]:
  613. run_compile()
  614. else:
  615. run_main(sys.argv[1:])