f2py2e.py 24 KB

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