[Numpy-svn] r4402 - in branches/numpy.scons/numpy: core distutils/scons distutils/scons/checkers distutils/scons/core
numpy-svn at scipy.org
numpy-svn at scipy.org
Tue Nov 6 04:19:06 EST 2007
Author: cdavid
Date: 2007-11-06 03:18:44 -0600 (Tue, 06 Nov 2007)
New Revision: 4402
Added:
branches/numpy.scons/numpy/distutils/scons/core/
branches/numpy.scons/numpy/distutils/scons/core/__init__.py
branches/numpy.scons/numpy/distutils/scons/core/custom_builders.py
branches/numpy.scons/numpy/distutils/scons/core/default.py
branches/numpy.scons/numpy/distutils/scons/core/extension.py
branches/numpy.scons/numpy/distutils/scons/core/extension_scons.py
branches/numpy.scons/numpy/distutils/scons/core/libinfo.py
branches/numpy.scons/numpy/distutils/scons/core/libinfo_scons.py
branches/numpy.scons/numpy/distutils/scons/core/numpyenv.py
branches/numpy.scons/numpy/distutils/scons/core/parser.py
branches/numpy.scons/numpy/distutils/scons/core/utils.py
Removed:
branches/numpy.scons/numpy/distutils/scons/custom_builders.py
branches/numpy.scons/numpy/distutils/scons/default.py
branches/numpy.scons/numpy/distutils/scons/extension.py
branches/numpy.scons/numpy/distutils/scons/extension_scons.py
branches/numpy.scons/numpy/distutils/scons/libinfo.py
branches/numpy.scons/numpy/distutils/scons/libinfo_scons.py
branches/numpy.scons/numpy/distutils/scons/numpyenv.py
branches/numpy.scons/numpy/distutils/scons/parser.py
branches/numpy.scons/numpy/distutils/scons/utils.py
Modified:
branches/numpy.scons/numpy/core/scons_support.py
branches/numpy.scons/numpy/distutils/scons/__init__.py
branches/numpy.scons/numpy/distutils/scons/checkers/custom_checkers.py
branches/numpy.scons/numpy/distutils/scons/checkers/perflib.py
branches/numpy.scons/numpy/distutils/scons/fortran_scons.py
Log:
Reogarnize a bit scons module
Modified: branches/numpy.scons/numpy/core/scons_support.py
===================================================================
--- branches/numpy.scons/numpy/core/scons_support.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/core/scons_support.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -10,7 +10,7 @@
do_generate_api as nowrap_do_generate_ufunc_api
from numpy.distutils.conv_template import process_str
-from numpy.distutils.scons.utils import _rsplit as rsplit, isstring
+from numpy.distutils.scons import rsplit, isstring
import SCons.Node
Modified: branches/numpy.scons/numpy/distutils/scons/__init__.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/__init__.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/__init__.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,9 +1,10 @@
-from numpyenv import GetNumpyEnvironment, GetNumpyOptions
-from libinfo_scons import NumpyCheckLib
-from libinfo import get_paths as scons_get_paths
+from core.numpyenv import GetNumpyEnvironment, GetNumpyOptions
+from core.libinfo_scons import NumpyCheckLib
+from core.libinfo import get_paths as scons_get_paths
+from core.extension import get_python_inc, get_pythonlib_dir
+from core.utils import isstring, rsplit
+
from checkers import CheckCBLAS, CheckLAPACK
-from extension import get_python_inc, get_pythonlib_dir
-from utils import isstring
from fortran_scons import CheckF77Verbose, CheckF77Clib, CheckF77Mangling
def test(level=1, verbosity=1):
Modified: branches/numpy.scons/numpy/distutils/scons/checkers/custom_checkers.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/checkers/custom_checkers.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/checkers/custom_checkers.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,12 +1,12 @@
#! /usr/bin/env python
-# Last Change: Tue Nov 06 04:00 PM 2007 J
+# Last Change: Tue Nov 06 06:00 PM 2007 J
# Module for custom, common checkers for numpy (and scipy)
import sys
import os.path
from distutils.util import get_platform
-from numpy.distutils.scons.libinfo import get_config_from_section, get_config
+from numpy.distutils.scons.core.libinfo import get_config_from_section, get_config
from numpy.distutils.scons.testcode_snippets import cblas_sgemm as cblas_src, \
c_sgemm as sunperf_src, lapack_sgesv
Modified: branches/numpy.scons/numpy/distutils/scons/checkers/perflib.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/checkers/perflib.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/checkers/perflib.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,5 +1,5 @@
#! /usr/bin/env python
-# Last Change: Tue Nov 06 01:00 PM 2007 J
+# Last Change: Tue Nov 06 06:00 PM 2007 J
# This module defines checkers for performances libs providing standard API,
# such as MKL (Intel), ATLAS, Sunperf (solaris and linux), Accelerate (Mac OS
@@ -12,7 +12,7 @@
from os.path import join as pjoin
from numpy.distutils.system_info import default_lib_dirs
-from numpy.distutils.scons.libinfo import get_config_from_section, get_config
+from numpy.distutils.scons.core.libinfo import get_config_from_section, get_config
from numpy.distutils.scons.testcode_snippets import cblas_sgemm as cblas_src, \
c_sgemm as sunperf_src, lapack_sgesv
Property changes on: branches/numpy.scons/numpy/distutils/scons/core
___________________________________________________________________
Name: svn:ignore
+ *.pyc
Added: branches/numpy.scons/numpy/distutils/scons/core/__init__.py
===================================================================
Copied: branches/numpy.scons/numpy/distutils/scons/core/custom_builders.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/custom_builders.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/default.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/default.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/extension.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/extension.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/extension_scons.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/extension_scons.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/libinfo.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/libinfo.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/libinfo_scons.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/libinfo_scons.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/numpyenv.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/numpyenv.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/parser.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/parser.py)
Copied: branches/numpy.scons/numpy/distutils/scons/core/utils.py (from rev 4396, branches/numpy.scons/numpy/distutils/scons/utils.py)
Deleted: branches/numpy.scons/numpy/distutils/scons/custom_builders.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/custom_builders.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/custom_builders.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,48 +0,0 @@
-from os.path import join as pjoin
-
-def NumpySharedLibrary(env, target, source, *args, **kw):
- """This builder is the same than SharedLibrary, except for the fact that it
- takes into account build dir info passed by distutils, and put the target at
- the right location in distutils build directory for correct installation."""
- source = [pjoin(env['build_dir'], i) for i in source]
- # XXX: why target is a list ? It is always true ?
- lib = env.SharedLibrary("$build_dir/%s" % target[0], source, *args, **kw)
-
- inst_lib = env.Install("$distutils_installdir", lib)
- return lib, inst_lib
-
-def NumpyPythonExtension(env, target, source, *args, **kw):
- """This builder is the same than PythonExtension, except for the fact that it
- takes into account build dir info passed by distutils, and put the target at
- the right location in distutils build directory for correct installation."""
- import SCons.Util
- newsource = []
- for i in source:
- if SCons.Util.is_String(i):
- newsource.append(pjoin(env['build_dir'], i))
- else:
- newsource.append(i)
- # XXX: why target is a list ? It is always true ?
- lib = env.PythonExtension("$build_dir/%s" % target[0], newsource, *args, **kw)
-
- inst_lib = env.Install("$distutils_installdir", lib)
- return lib, inst_lib
-
-
-def NumpyCtypes(env, target, source, *args, **kw):
- """This builder is essentially the same than SharedLibrary, but should be
- used for libraries which will only be used through ctypes.
-
- In particular, it does not install .exp/.lib files on windows. """
- source = [pjoin(env['build_dir'], i) for i in source]
- # XXX: why target is a list ? It is always true ?
- # XXX: handle cases where SHLIBPREFIX is in args
- lib = env.SharedLibrary("$build_dir/%s" % target[0],
- source,
- SHLIBPREFIX = '',
- *args,
- **kw)
- lib = [i for i in lib if not (str(i).endswith('.exp') or str(i).endswith('.lib')) ]
- inst_lib = env.Install("$distutils_installdir", lib)
- return lib, inst_lib
-
Deleted: branches/numpy.scons/numpy/distutils/scons/default.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/default.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/default.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,174 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Mon Nov 05 06:00 PM 2007 J
-import sys
-import distutils.sysconfig
-
-# This is a copy of scons/Tools/__init__.py, because scons does not offer any
-# public api for this
-def tool_list(platform):
- """platform should be the value returned by enbv['PLATFORM'], not
- sys.platform !!!!."""
- # Here, we set the list of default tools as used by numpy.distutils.scons. This
- # is ripped of scons, because scons does not provide a way to get separate
- # default lists for separate tools (e.g linker, C compiler, etc...)
-
- if str(platform) == 'win32':
- "prefer Microsoft tools on Windows"
- linkers = ['mslink', 'gnulink', 'ilink', 'linkloc', 'ilink32' ]
- c_compilers = ['msvc', 'mingw', 'gcc', 'intelc', 'icl', 'icc', 'cc', 'bcc32' ]
- cxx_compilers = ['msvc', 'intelc', 'icc', 'g++', 'c++', 'bcc32' ]
- assemblers = ['masm', 'nasm', 'gas', '386asm' ]
- fortran_compilers = ['g77', 'ifl', 'cvf', 'f95', 'f90', 'fortran']
- ars = ['mslib', 'ar', 'tlib']
- elif str(platform) == 'os2':
- "prefer IBM tools on OS/2"
- linkers = ['ilink', 'gnulink', 'mslink']
- c_compilers = ['icc', 'gcc', 'msvc', 'cc']
- cxx_compilers = ['icc', 'g++', 'msvc', 'c++']
- assemblers = ['nasm', 'masm', 'gas']
- fortran_compilers = ['ifl', 'g77']
- ars = ['ar', 'mslib']
- elif str(platform) == 'irix':
- "prefer MIPSPro on IRIX"
- linkers = ['sgilink', 'gnulink']
- c_compilers = ['sgicc', 'gcc', 'cc']
- cxx_compilers = ['sgic++', 'g++', 'c++']
- assemblers = ['as', 'gas']
- fortran_compilers = ['f95', 'f90', 'f77', 'g77', 'fortran']
- ars = ['sgiar']
- elif str(platform) == 'sunos':
- "prefer Forte tools on SunOS"
- linkers = ['sunlink', 'gnulink']
- c_compilers = ['suncc', 'gcc', 'cc']
- cxx_compilers = ['sunc++', 'g++', 'c++']
- assemblers = ['as', 'gas']
- fortran_compilers = ['f95', 'f90', 'f77', 'g77', 'fortran']
- ars = ['sunar']
- elif str(platform) == 'hpux':
- "prefer aCC tools on HP-UX"
- linkers = ['hplink', 'gnulink']
- c_compilers = ['hpcc', 'gcc', 'cc']
- cxx_compilers = ['hpc++', 'g++', 'c++']
- assemblers = ['as', 'gas']
- fortran_compilers = ['f95', 'f90', 'f77', 'g77', 'fortran']
- ars = ['ar']
- elif str(platform) == 'aix':
- "prefer AIX Visual Age tools on AIX"
- linkers = ['aixlink', 'gnulink']
- c_compilers = ['aixcc', 'gcc', 'cc']
- cxx_compilers = ['aixc++', 'g++', 'c++']
- assemblers = ['as', 'gas']
- fortran_compilers = ['f95', 'f90', 'aixf77', 'g77', 'fortran']
- ars = ['ar']
- elif str(platform) == 'darwin':
- "prefer GNU tools on Mac OS X, except for some linkers and IBM tools"
- linkers = ['applelink', 'gnulink']
- c_compilers = ['gcc', 'cc']
- cxx_compilers = ['g++', 'c++']
- assemblers = ['as']
- fortran_compilers = ['f95', 'f90', 'g77']
- ars = ['ar']
- else:
- "prefer GNU tools on all other platforms"
- linkers = ['gnulink', 'mslink', 'ilink']
- c_compilers = ['gcc', 'msvc', 'intelc', 'icc', 'cc']
- cxx_compilers = ['g++', 'msvc', 'intelc', 'icc', 'c++']
- assemblers = ['gas', 'nasm', 'masm']
- fortran_compilers = ['f95', 'f90', 'g77', 'ifort', 'ifl', 'fortran']
- ars = ['ar', 'mslib']
-
- other_tools = ['BitKeeper', 'CVS', 'dmd', 'dvipdf', 'dvips', 'gs', 'jar',
- 'javac', 'javah', 'latex', 'lex', 'm4', 'midl', 'msvs', 'pdflatex',
- 'pdftex', 'Perforce', 'RCS', 'rmic', 'rpcgen', 'SCCS', 'swig',
- 'tar', 'tex', 'yacc', 'zip']
- return linkers, c_compilers, cxx_compilers, assemblers, fortran_compilers, \
- ars, other_tools
-
-# Handling compiler configuration: only flags which change how to build object
-# files. Nothing related to linking, search path, etc... should be given here.
-# Basically, limit yourself to optimization/debug/warning flags.
-
-# XXX: customization from site.cfg or other ?
-class CompilerConfig:
- def __init__(self, optim = None, warn = None, debug = None, debug_symbol =
- None, thread = None, extra = None):
- # XXX: several level of optimizations ?
- self.optim = optim
- # XXX: several level of warnings ?
- self.warn = warn
- # To enable putting debugging info in binaries
- self.debug_symbol = debug_symbol
- # To enable friendly debugging
- self.debug = debug
- # XXX
- self.thread = thread
- # XXX
- self.extra = extra
-
- def get_flags_dict(self):
- d = {'NUMPY_OPTIM_CFLAGS' : self.optim,
- 'NUMPY_WARN_CFLAGS' : self.warn,
- 'NUMPY_THREAD_CFLAGS' : self.thread,
- 'NUMPY_EXTRA_CFLAGS' : self.debug,
- 'NUMPY_DEBUG_CFLAGS' : self.debug,
- 'NUMPY_DEBUG_SYMBOL_CFLAGS' : self.debug_symbol}
- for k, v in d.items():
- if v is None:
- d[k] = []
- return d
-
-# It seems that scons consider any option with space in it as a multi option,
-# which breaks command line options. So just don't put space.
-def get_cc_config(name):
- if name == 'gcc':
- if distutils.sysconfig.get_config_vars('LDFLAGS')[0].find('-pthread'):
- thread = ['-pthread']
- else:
- thread = []
- cfg = CompilerConfig(optim = ['-O2', '-fno-strict-aliasing', '-DNDEBUG'],
- warn = ['-Wall', '-Wstrict-prototypes'],
- debug_symbol = ['-g'],
- thread = thread)
- elif name == 'intelc':
- if sys.platform[:5] == 'win32':
- raise NotImplementedError('FIXME: intel compiler on windows not '\
- ' supported yet')
-
- cfg = CompilerConfig(optim = ['-O2', '-fno-strict-aliasing', '-DNDEBUG'],
- warn = ['-Wall', '-Wstrict-prototypes'],
- debug_symbol = ['-g'],
- thread = ['-pthread'])
- elif name == 'msvc':
- # XXX: distutils part of customization:
- # if self.__arch == "Intel":
- # self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' , '/DNDEBUG']
- # self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX', '/Z7', '/D_DEBUG']
- # else:
- # # Win64
- # self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' ,
- # '/DNDEBUG']
- # self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-',
- # '/Z7', '/D_DEBUG']
- #
- # self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']
- # if self.__version >= 7:
- # self.ldflags_shared_debug = [
- # '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG'
- # ]
- # else:
- # self.ldflags_shared_debug = [
- # '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG'
- # ]
- # self.ldflags_static = [ '/nologo']
-
- cfg = CompilerConfig(optim = ['/Ox', '/DNDEBUG'],
- warn = ['/W3', '/Wall'],
- thread = ['/MD', '/GX'],
- extra = ['/nologo'])
- else:
- # For not yet supported compiler, just put everything in optims from
- # distutils
- cfg = CompilerConfig(optims =
- distutils.sysconfig.get_config_vars('CFLAGS'))
-
- return cfg
Deleted: branches/numpy.scons/numpy/distutils/scons/extension.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/extension.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/extension.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,25 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Tue Oct 09 03:00 PM 2007 J
-
-# Module for support to build python extension. KEEP THIS INDEPENDANT OF SCONS
-
-# XXX: we should avoid clashing between distutils and numpy.distutils. Maybe by
-# defining our own functions here, and accessing any info related to python
-# build option and co from here only.
-import sys
-import os
-from os.path import join as pjoin
-
-from distutils.sysconfig import get_python_version, get_python_inc, get_config_vars
-
-def get_pythonlib_dir():
- """Returns a list of path to look for the python engine library
- (pythonX.X.lib on win32, libpythonX.X.so on unix, etc...)."""
- if os.name == 'nt':
- return [pjoin(sys.exec_prefix, 'libs')]
- else:
- return [pjoin(sys.exec_prefix, 'lib')]
-
-if __name__ == '__main__':
- print "Python version is %s" % get_python_version()
- print "Python include dir is %s" % get_python_inc()
Deleted: branches/numpy.scons/numpy/distutils/scons/extension_scons.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/extension_scons.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/extension_scons.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,43 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Fri Oct 19 11:00 AM 2007 J
-
-# Module for support to build python extension. scons specific code goes here.
-import sys
-from copy import deepcopy
-
-from extension import get_pythonlib_dir, get_python_inc
-
-def built_with_mstools(env):
- """Return True if built with MS tools (compiler + linker)."""
- return env.has_key('MSVS')
-
-def PythonExtension(env, target, source, *args, **kw):
- # XXX Check args and kw
- # XXX: Some things should not be set here...
- if env.has_key('LINKFLAGS'):
- LINKFLAGS = deepcopy(env['LINKFLAGS'])
- else:
- LINKFLAGS = []
-
- if env.has_key('CPPPATH'):
- CPPPATH = deepcopy(env['CPPPATH'])
- else:
- CPPPATH = []
-
- CPPPATH.append(get_python_inc())
- if sys.platform == 'win32':
- if built_with_mstools(env):
- # XXX: We add the path where to find python2.5.lib (or any other
- # version, of course). This seems to be necessary for MS compilers.
- env.AppendUnique(LIBPATH = get_pythonlib_dir())
- elif sys.platform == "darwin":
- # XXX: When those should be used ? (which version of Mac OS X ?)
- LINKFLAGS += ' -undefined dynamic_lookup '
-
- # Use LoadableModule because of Mac OS X
- wrap = env.LoadableModule(target, source, SHLIBPREFIX = '',
- LDMODULESUFFIX = '$PYEXTSUFFIX',
- SHLIBSUFFIX = '$PYEXTSUFFIX',
- LINKFLAGS = LINKFLAGS,
- CPPPATH = CPPPATH, *args, **kw)
- return wrap
Modified: branches/numpy.scons/numpy/distutils/scons/fortran_scons.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/fortran_scons.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/fortran_scons.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,4 +1,4 @@
-# Last Change: Tue Nov 06 05:00 PM 2007 J
+# Last Change: Tue Nov 06 06:00 PM 2007 J
import os
import sys
import string
@@ -6,7 +6,7 @@
from os.path import basename, join as pjoin, dirname
from copy import deepcopy
-from utils import popen_wrapper
+from numpy.distutils.scons.core.utils import popen_wrapper
from fortran import parse_f77link, check_link_verbose
#-----------------
Deleted: branches/numpy.scons/numpy/distutils/scons/libinfo.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/libinfo.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/libinfo.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,117 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Mon Oct 29 03:00 PM 2007 J
-
-# Module for support to look for external code (replacement of
-# numpy.distutils.system_info). KEEP THIS INDEPENDANT OF SCONS !
-import os
-import ConfigParser
-
-from numpy.distutils.system_info import default_lib_dirs, \
- default_include_dirs, default_src_dirs, get_standard_file
-
-# Think about a cache mechanism, to avoid reparsing the config file everytime.
-def get_config():
- """ This tries to read .cfg files in several locations, and merge its
- information into a ConfigParser object for the first found file.
-
- Returns the ConfigParser instance. This copies the logic in system_info
- from numpy.distutils."""
- # Below is the feature we are copying from numpy.distutils:
- #
- # The file 'site.cfg' is looked for in
-
- # 1) Directory of main setup.py file being run.
- # 2) Home directory of user running the setup.py file as ~/.numpy-site.cfg
- # 3) System wide directory (location of this file...)
-
- # The first one found is used to get system configuration options The
- # format is that used by ConfigParser (i.e., Windows .INI style). The
- # section DEFAULT has options that are the default for each section. The
- # available sections are fftw, atlas, and x11. Appropiate defaults are
- # used if nothing is specified.
-
- section = 'DEFAULT'
- defaults = {}
- defaults['libraries'] = ''
- defaults['library_dirs'] = os.pathsep.join(default_lib_dirs)
- defaults['include_dirs'] = os.pathsep.join(default_include_dirs)
- defaults['src_dirs'] = os.pathsep.join(default_src_dirs)
- cp = ConfigParser.ConfigParser(defaults)
- files = []
- files.extend(get_standard_file('.numpy-site.cfg'))
- files.extend(get_standard_file('site.cfg'))
-
- def parse_config_files():
- cp.read(files)
- if not cp.has_section(section):
- cp.add_section(section)
-
- parse_config_files()
- return cp, files
-
-def parse_config_param(var):
- """Given var, the output of ConfirParser.get(section, name), returns a list
- of each item of its content."""
- varl = var.split(',')
- return [i.strip() for i in varl]
-
-def get_paths(var):
- """Given var, the output of ConfirParser.get(section, name), returns a list
- of each item of its content, assuming the content is a list of directoris.
-
- Example: if var is foo:bar, it will return ['foo', 'bar'] on posix."""
- return var.split(os.pathsep)
-
-def get_config_from_section(siteconfig, section):
- """For the given siteconfig and section, return the found information.
-
- Returns a tuple (info, found), where:
- info : tuple (cpppath, libs, libpath), containing a list of path or libraries
- found: 1 if the section was found, 0 otherwise."""
- if siteconfig.has_section(section):
- try:
- libpath = get_paths(siteconfig.get(section, 'library_dirs'))
- except ConfigParser.NoSectionError, e:
- libpath = []
-
- try:
- cpppath = get_paths(siteconfig.get(section, 'include_dirs'))
- except ConfigParser.NoSectionError, e:
- cpppath = []
-
- try:
- libs = parse_config_param(siteconfig.get(section, 'libraries'))
- except ConfigParser.NoSectionError, e:
- libs = []
- return (cpppath, libs, libpath), 1
- else:
- return ([], [], []), 0
-
-def get_func_link_src(func, includes = None):
- """Given a function, return the source code to compile and link to
- test for this symbol.
-
- includes is a list of (optional) headers"""
- src = []
- if includes:
- src.extend([r'#include <%s>\n' for h in includes])
-
- src.append(r"""
-#undef %(func)s
-
-#ifdef __cplusplus
-extern "C"
-#endif
-char %(func)s ();
-
-int
-main ()
-{
- return %(func)s();
-}
-""" % {'func' : func})
-
- return '\n'.join(src)
-
-if __name__ == '__main__':
- pass
Deleted: branches/numpy.scons/numpy/distutils/scons/libinfo_scons.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/libinfo_scons.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/libinfo_scons.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,196 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Fri Oct 26 04:00 PM 2007 J
-
-# Module for support to look for external code (replacement of
-# numpy.distutils.system_info). scons dependant code.
-import ConfigParser
-from copy import deepcopy
-
-from libinfo import get_config, get_paths, parse_config_param
-from utils import get_empty
-
-_SYMBOL_DEF_STR = """
-#ifdef __cplusplus
-extern "C"
-#endif
-char %s();\n"""
-
-_MAIN_CALL_CENTER = """
-int main(int argc, char** argv)
-{
- %s
- return 0;
-}\n """
-
-def _CheckLib(context, libs, symbols, header, language, section, siteconfig,
- libpath, cpppath, verbose):
- """Implementation for checking a list of symbols, with libs.
-
- Assumes that libs, symbol, header, libpath and cpppath are sequences (list
- or tuples). DO NOT USE DIRECTLY IN SCONSCRIPT !!!"""
- # XXX: sanitize API for section/siteconfig option: if section is not given,
- # can we just say to ignore the sitecfg ?
- if not siteconfig:
- siteconfig, cfgfiles = get_config()
-
- def get_descr():
- try:
- descr = siteconfig.items(section)
- except ConfigParser.NoSectionError:
- descr = ""
- sdescr = ""
- for i in descr:
- sdescr += str(i) + '\n'
- return sdescr
-
- # Generate the source string of the conftest
- src = ""
- callstr = ""
-
- if symbols:
- for s in symbols:
- # XXX: should put undef here (ala autoconf)
- src += _SYMBOL_DEF_STR % s
- callstr += "%s();" % s
-
- src += _MAIN_CALL_CENTER % callstr
- # HUGE HACK: we want this test to depend on site.cfg files obviously, since
- # a change in them can change the libraries tested. But Depends does not
- # seem to work in configuration context, and I don't see any simple way to
- # have the same functionality. So I put the configuration we got from
- # get_config into the source code, such as a change in site.cfg will change
- # the source file, and thus taken into account to decide whether to rebuild
- # from tjhe SconfTaskMaster point of view.
-
- # XXX: I put the content between #if 0 / #endif, which is the most portable
- # way I am aware of for multilines comments in C and C++ (this is also
- # recommended in C++ portability guide of mozilla for nested comments,
- # which may happen here). This is also the most robust, since it seems
- # unlikely to have any #endif somewhere in the return value of get_descr.
- src += "#if 0\n"
- src += get_descr()
- src += "\n#endif\n"
-
- # XXX: handle autoadd
- # XXX: handle extension
- extension = '.c'
-
- if section and siteconfig:
- #print "Checking %s from section %s" % (libs[0], section)
- res = _check_lib_section(context, siteconfig, section, src, libs,
- libpath, cpppath)
- else:
- oldLIBS = context.env.has_key('LIBS') and deepcopy(context.env['LIBS'])
- context.env.Append(LIBS = libs)
- res = context.TryLink(src, '.c')
- if not res:
- context.env.Replace(LIBS = oldLIBS)
-
- return res
-
-
-def NumpyCheckLib(context, libs, symbols = None, header = None,
- language = None, section = None, siteconfig = None, name = None, verbose = None):
- """Check for symbol in libs.
-
- This is the general purpose replacement for numpy.distutils.system_info. It
- uses the options in siteconfig so that search path can be overwritten in
- *.cfg files (using section given by section argument). If siteconfig is
- None, it does uses get_config function to get the configuration, which
- gives the old numpy.distutils behaviour to get options.
-
-
- Convention: if the section has *dirs parameters, it will use them all in
- one pass, e.g if library_dirs is ['/usr/local/lib', '/usr/local/mylib'], it
- will try to link the given libraries by appending both directories to the
- LIBPATH."""
- #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- # This is really preliminary, and needs a lot of love before being in good
- # shape !!!!!
- #
- # Biggest problem: how to show information about found libraries ? Since
- # they are found implicitely through build tools (compiler and linker), we
- # can not give explicit information. IMHO (David Cournapeau), it is better
- # to find them implicitely because it is much more robust. But for the info...
- #
- # This needs testing, too.
- #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
- from SCons.Util import is_List
-
- env = context.env
-
- # XXX: would be nice for each extension to add an option to
- # command line.
- # XXX: handle env var
- # XXX: handle language
- if language:
- raise NotImplementedError("FIXME: language selection not implemented yet !")
-
- # Make sure libs and symbols are lists
- if libs and not is_List(libs):
- libs = [libs]
- if symbols and not is_List(symbols):
- symbols = [symbols]
-
- if not name:
- name = libs[0]
-
- # Display message
- if symbols:
- sbstr = ', '.join(symbols)
- context.Message('Checking for symbol(s) %s in %s... ' % (sbstr, name))
- else:
- context.Message('Checking for %s... ' % name)
-
- # Call the implementation
- libpath = None
- cpppath = None
- res = _CheckLib(context, libs, symbols, header, language, section,
- siteconfig, libpath, cpppath, verbose)
- context.Result(res)
- return res
-
-def _check_lib_section(context, siteconfig, section, src, libs, libpath, cpppath):
- # Convention: if an option is found in site.cfg for the given
- # section, it takes precedence on the arguments libs, libpath,
- # cpppath.
- res = 1
-
- # XXX: refactor this mess
- try:
- newLIBPATH = get_paths(siteconfig.get(section, 'library_dirs'))
- except ConfigParser.NoSectionError, e:
- if libpath:
- newLIBPATH = libpath
- else:
- newLIBPATH = []
-
- try:
- newCPPPATH = get_paths(siteconfig.get(section, 'include_dirs'))
- except ConfigParser.NoSectionError, e:
- if cpppath:
- newCPPPATH = cpppath
- else:
- newCPPPATH = []
-
- try:
- newLIBS = parse_config_param(siteconfig.get(section, 'libraries'))
- except ConfigParser.NoSectionError, e:
- if libs:
- newLIBS = libs
- else:
- newLIBS = []
-
- lastLIBPATH = get_empty(context.env,'LIBPATH')
- lastLIBS = get_empty(context.env,'LIBS')
- lastCPPPATH = get_empty(context.env,'CPPPATH')
- context.env.Append(LIBPATH = newLIBPATH)
- context.env.Append(LIBS = newLIBS)
- context.env.Append(CPPPATH = newCPPPATH)
- res *= context.TryLink(src, '.c')
- if not res:
- context.env.Replace(LIBS = lastLIBS,
- LIBPATH = lastLIBPATH,
- CPPPATH = lastCPPPATH)
-
- return res
Deleted: branches/numpy.scons/numpy/distutils/scons/numpyenv.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/numpyenv.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/numpyenv.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,240 +0,0 @@
-# Last Changed: .
-import os.path
-from os.path import join as pjoin, dirname as pdirname
-import sys
-
-from distutils.sysconfig import get_config_vars
-
-from numpy.distutils.misc_util import get_scons_build_dir, get_scons_configres_dir,\
- get_scons_configres_filename
-
-from default import tool_list, get_cc_config
-from custom_builders import NumpySharedLibrary, NumpyCtypes, NumpyPythonExtension
-from libinfo import get_config
-from extension_scons import PythonExtension
-
-from numpy.distutils.scons.tools.substinfile import TOOL_SUBST
-
-def pyplat2sconsplat():
- # XXX: should see how env['PLATFORM'] is defined, make this a dictionary
- if sys.platform[:5] == 'linux':
- return 'posix'
- elif sys.platform[:5] == 'sunos':
- return 'sunos'
- else:
- return sys.platform
-
-DEF_LINKERS, DEF_C_COMPILERS, DEF_CXX_COMPILERS, DEF_ASSEMBLERS, \
-DEF_FORTRAN_COMPILERS, DEF_ARS, DEF_OTHER_TOOLS = tool_list(pyplat2sconsplat())
-
-def is_cc_suncc(fullpath):
- """Return true if the compiler is suncc."""
- # I wish there was a better way: we launch suncc -V, read the output, and
- # returns true if Sun is found in the output. We cannot check the status
- # code, because the compiler does not seem to have a way to do nothing
- # while returning success (0).
-
- import os
- import re
- suncc = re.compile('Sun C')
- # Redirect stderr to stdout
- cmd = fullpath + ' -V 2>&1'
- out = os.popen(cmd)
- cnt = out.read()
- st = out.close()
-
- return suncc.search(cnt)
-
-def GetNumpyOptions(args):
- """Call this with args=ARGUMENTS to take into account command line args."""
- from SCons.Options import Options
-
- opts = Options(None, args)
- # Add directories related info
- opts.Add('pkg_name', 'name of the package (including parent package if any)', '')
- opts.Add('src_dir', 'src dir relative to top called', '.')
- opts.Add('build_prefix', 'build prefix (NOT including the package name)',
- get_scons_build_dir())
- opts.Add('distutils_libdir',
- 'build dir for libraries of distutils (NOT including the package name)',
- pjoin('build', 'lib'))
- opts.Add('include_bootstrap',
- "include directories for boostraping numpy (if you do not know" \
- " what that means, you don't need it)" ,
- '')
-
- # Add compiler related info
- opts.Add('cc_opt', 'name of C compiler', '')
- opts.Add('cc_opt_path', 'path of the C compiler set in cc_opt', '')
-
- opts.Add('f77_opt', 'name of F77 compiler', '')
- opts.Add('f77_opt_path', 'path of the F77 compiler set in cc_opt', '')
-
- return opts
-
-def customize_cc(name, env):
- """Customize env options related to the given tool."""
- cfg = get_cc_config(name)
- env.AppendUnique(**cfg.get_flags_dict())
-
-def GetNumpyEnvironment(args):
- env = _GetNumpyEnvironment(args)
- env.AppendUnique(CFLAGS = env['NUMPY_WARN_CFLAGS'] + env['NUMPY_OPTIM_CFLAGS'] +\
- env['NUMPY_DEBUG_SYMBOL_CFLAGS'] +\
- env['NUMPY_EXTRA_CFLAGS'] +\
- env['NUMPY_THREAD_CFLAGS'])
- return env
-
-def _GetNumpyEnvironment(args):
- """Call this with args = ARGUMENTS."""
- from SCons.Environment import Environment
- from SCons.Tool import Tool, FindTool, FindAllTools
- from SCons.Script import BuildDir, Help
-
- # XXX: I would prefer subclassing Environment, because we really expect
- # some different behaviour than just Environment instances...
- opts = GetNumpyOptions(args)
-
- # Get the python extension suffix
- # XXX this should be defined somewhere else. Is there a way to reliably get
- # all the necessary informations specific to python extensions (linkflags,
- # etc...) dynamically ?
- pyextsuffix = get_config_vars('SO')
-
- # We set tools to an empty list, to be sure that the custom options are
- # given first. We have to
- env = Environment(options = opts, tools = [], PYEXTSUFFIX = pyextsuffix)
-
- # Add the file substitution tool
- TOOL_SUBST(env)
-
- # Setting dirs according to command line options
- env.AppendUnique(build_dir = pjoin(env['build_prefix'], env['src_dir']))
- env.AppendUnique(distutils_installdir = pjoin(env['distutils_libdir'],
- env['pkg_name']))
-
- # ===============================================
- # Setting tools according to command line options
-
- # XXX: how to handle tools which are not in standard location ? Is adding
- # the full path of the compiler enough ? (I am sure some compilers also
- # need LD_LIBRARY_SHARED and other variables to be set, too....)
- if len(env['cc_opt']) > 0:
- try:
- if len(env['cc_opt_path']) > 0:
- if env['cc_opt'] == 'intelc':
- # Intel Compiler SCons.Tool has a special way to set the
- # path, o we use this one instead of changing
- # env['ENV']['PATH'].
- t = Tool(env['cc_opt'],
- topdir = os.path.split(env['cc_opt_path'])[0])
- t(env)
- customize_cc(t.name, env)
- else:
- if is_cc_suncc(pjoin(env['cc_opt_path'], env['cc_opt'])):
- env['cc_opt'] = 'suncc'
- # XXX: what is the right way to add one directory in the
- # PATH ? (may not work on windows).
- t = Tool(env['cc_opt'])
- t(env)
- customize_cc(t.name, env)
- if sys.platform == 'win32':
- env['ENV']['PATH'] += ';%s' % env['cc_opt_path']
- else:
- env['ENV']['PATH'] += ':%s' % env['cc_opt_path']
- except EnvironmentError, e:
- # scons could not understand cc_opt (bad name ?)
- raise AssertionError("SCONS: Could not initialize tool ? Error is %s" % \
- str(e))
- else:
- t = Tool(FindTool(DEF_C_COMPILERS))
- t(env)
- customize_cc(t.name, env)
-
- # F77 compiler
- if len(env['f77_opt']) > 0:
- try:
- if len(env['f77_opt_path']) > 0:
- # XXX: what is the right way to add one directory in the
- # PATH ? (may not work on windows).
- t = Tool(env['f77_opt'], toolpath = ['numpy/distutils/scons/tools'])
- t(env)
- if sys.platform == 'win32':
- env['ENV']['PATH'] += ';%s' % env['f77_opt_path']
- else:
- env['ENV']['PATH'] += ':%s' % env['f77_opt_path']
- except EnvironmentError, e:
- # scons could not understand cc_opt (bad name ?)
- raise AssertionError("SCONS: Could not initialize tool ? Error is %s" % \
- str(e))
- # XXX: really have to understand how fortran compilers work in scons...
- env['F77'] = env['_FORTRAND']
- else:
- raise NotImplementedError('FIXME: Support for env wo fcompiler not tested yet !')
- #t = Tool(FindTool(DEF_FORTRAN_COMPILERS))
- #t(env)
-
- # XXX: Really, we should use our own subclass of Environment, instead of
- # adding Numpy* functions !
-
- # Put config code and log in separate dir for each subpackage
- from utils import curry
- NumpyConfigure = curry(env.Configure,
- conf_dir = pjoin(env['build_dir'], '.sconf'),
- log_file = pjoin(env['build_dir'], 'config.log'))
- env.NumpyConfigure = NumpyConfigure
-
- # XXX: Huge, ugly hack ! SConsign needs an absolute path or a path
- # relative to where the SConstruct file is. We have to find the path of
- # the build dir relative to the src_dir: we add n .., where n is the number
- # of occureant of the path separator in the src dir.
- def get_build_relative_src(srcdir, builddir):
- n = srcdir.count(os.sep) + 1
- return pjoin(os.sep.join([os.pardir for i in range(n)]), builddir)
- sconsign = pjoin(get_build_relative_src(env['src_dir'],
- env['build_dir']),
- '.sconsign.dblite')
- env.SConsignFile(sconsign)
-
- # ========================================================================
- # Adding default tools for the one we do not customize: mingw is special
- # according to scons, don't ask me why, but this does not work as expected
- # for this tool.
- if not env['cc_opt'] == 'mingw':
- for i in [DEF_LINKERS, DEF_CXX_COMPILERS, DEF_ASSEMBLERS, DEF_ARS]:
- t = FindTool(i, env) or i[0]
- Tool(t)(env)
-
- for t in FindAllTools(DEF_OTHER_TOOLS, env):
- Tool(t)(env)
-
- try:
- env['ENV']['HOME'] = os.environ['HOME']
- except KeyError:
- pass
-
- # Adding custom builder
- env['BUILDERS']['NumpySharedLibrary'] = NumpySharedLibrary
- env['BUILDERS']['NumpyCtypes'] = NumpyCtypes
- env['BUILDERS']['PythonExtension'] = PythonExtension
- env['BUILDERS']['NumpyPythonExtension'] = NumpyPythonExtension
-
- # Setting build directory according to command line option
- if len(env['src_dir']) > 0:
- BuildDir(env['build_dir'], env['src_dir'])
- else:
- BuildDir(env['build_dir'], '.')
-
- # Generate help (if calling scons directly during debugging, this could be useful)
- Help(opts.GenerateHelpText(env))
-
- # Getting the config options from *.cfg files
- config = get_config()
- env['NUMPY_SITE_CONFIG'] = config
-
- # This will be used to keep configuration information on a per package basis
- env['NUMPY_PKG_CONFIG'] = {}
- env['NUMPY_PKG_CONFIG_FILE'] = pjoin(get_scons_configres_dir(), env['src_dir'],
- get_scons_configres_filename())
-
- return env
Deleted: branches/numpy.scons/numpy/distutils/scons/parser.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/parser.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/parser.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,117 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Mon Nov 05 07:00 PM 2007 J
-import re
-import shlex
-
-# Those are obtained from distutils.sysconfig.get_config_vars('CFLAGS')
-tiger_x86_cflags = r'-arch ppc -arch i386 -sysroot '\
-'/Developers/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double '\
-'-no-cpp-precomp -DNDEBUG -f -O3'
-linux_x86_cflags = r'-fno-strict-aliasing -DNDEBUG -g -O2 -Wall '\
- '-Wstrict-prototypes'
-linux_x86_ldflags = r'-pthread -shared -Wl,-O1'
-
-# List of arguments taking an option (with space)
-cflags_argument_options = [r'-arch', r'-sysroot']
-ldflags_argument_options = [r'-arch', r'-sysroot', r'-L']
-
-def is_option(token):
- return token.startswith('-')
-
-def has_argument(token):
- """Returns True if current token is an option expecting an argument."""
- for i in cflags_argument_options:
- if token.startswith(i):
- return True
- return False
-
-def cc_process_argument(lexer, token):
- """Merge subsequent tokens while no option flag is detected."""
- token_list = [token]
- token = lexer.get_token()
- while token is not None and not is_option(token):
- token_list.append(token)
- token = lexer.get_token()
- return token_list, token
-
-def ld_process_argument(lexer, token):
- """Merge subsequent tokens while no option flag is detected."""
- token_list = [token]
- token = lexer.get_token()
- while token is not None and not is_option(token):
- token_list.append(token)
- token = lexer.get_token()
- return token_list, token
-
-def parse_posix_ld_token(lexer, token):
- if not token:
- return None
-
- if has_argument(token):
- token_list, next_token = ld_process_argument(lexer, token)
- token = ' '.join(token_list)
- else:
- next_token = lexer.get_token()
-
- if token.startswith('-L'):
- print "token %s is a libpath flag" % token
- elif token.startswith('-W'):
- print "token %s is a linker flag" % token
- elif token.startswith('-O'):
- print "token %s is a optim flag" % token
- elif token.startswith('-g'):
- print "token %s is a debug related flag" % token
- elif token.startswith('-pthread'):
- print "token %s is a thread related flag" % token
- else:
- print "token %s is unknown (extra)" % token
-
- return next_token
-
-def parse_posix_cc_token(lexer, token):
- if not token:
- return None
-
- if has_argument(token):
- token_list, next_token = cc_process_argument(lexer, token)
- token = ' '.join(token_list)
- else:
- next_token = lexer.get_token()
-
- if token.startswith('-W'):
- print "token %s is a warning flag" % token
- elif token.startswith('-D'):
- print "token %s is a define flag" % token
- elif token.startswith('-f'):
- print "token %s is a compilation flag" % token
- elif token.startswith('-O'):
- print "token %s is a optim flag" % token
- elif token.startswith('-g'):
- print "token %s is a debug related flag" % token
- elif token.startswith('-pthread'):
- print "token %s is a thread related flag" % token
- else:
- print "token %s is unknown (extra)" % token
-
- return next_token
-
-if __name__ == '__main__':
- def parse_cflags(flags):
- a = shlex.shlex(flags, posix = True)
- a.whitespace_split = True
- t = a.get_token()
- while t:
- t = parse_posix_cc_token(a, t)
-
- def parse_ldflags(flags):
- a = shlex.shlex(flags, posix = True)
- a.whitespace_split = True
- t = a.get_token()
- while t:
- t = parse_posix_ld_token(a, t)
-
- for i in [linux_x86_cflags, tiger_x86_cflags]:
- parse_cflags(i)
-
- for i in [linux_x86_ldflags]:
- parse_ldflags(i)
Deleted: branches/numpy.scons/numpy/distutils/scons/utils.py
===================================================================
--- branches/numpy.scons/numpy/distutils/scons/utils.py 2007-11-06 09:04:10 UTC (rev 4401)
+++ branches/numpy.scons/numpy/distutils/scons/utils.py 2007-11-06 09:18:44 UTC (rev 4402)
@@ -1,117 +0,0 @@
-#! /usr/bin/env python
-# Last Change: Mon Oct 29 07:00 PM 2007 J
-
-# This module defines various utilities used throughout the scons support
-# library.
-
-import os
-import re
-
-from copy import deepcopy
-
-_START_WITH_MINUS = re.compile('^\s*-')
-
-def popen_wrapper(cmd, merge = False):
- """This works like popen, but it returns both the status and the output.
-
- If merge is True, then output contains both stdout and stderr.
-
- Returns: (st, out), where st is an integer (the return status of the
- subprocess, and out the string of the output).
-
- NOTE:
- - it tries to be robust to find non existing command. For example, is
- cmd starts with a minus, a nonzero status is returned, and no junk is
- displayed on the interpreter stdout."""
- if _START_WITH_MINUS.match(cmd):
- return 1, ''
- if merge:
- # XXX: I have a bad feeling about this. Does it really work reliably on
- # all supported platforms ?
- cmd += ' 2>& 1 '
- output = os.popen(cmd)
- out = output.read()
- st = output.close()
- if st:
- status = st
- else:
- status = 0
-
- return status, out
-
-def get_empty(dict, key):
- """Assuming dict is a dictionary with lists as values, returns an empty
- list if key is not found, or a (deep) copy of the existing value if it
- does."""
- try:
- return deepcopy(dict[key])
- except KeyError, e:
- return []
-
-def rsplit(s, sep, max = -1):
- """Equivalent of rsplit, but works on 2.3."""
- try:
- return s.rsplit(sep, max)
- except AttributeError:
- return _rsplit(s, sep, max)
-
-def _rsplit(s, sep, max):
- """Equivalent of rsplit, but works on 2.3."""
- l = s.split(sep)
- if len(l) < 2 or max == 0:
- return [s]
- elif max < 0:
- return l[-len(l):]
- else:
- st = sep.join(l[0:-max])
- return [st] + l[-max:]
-
-class curry:
- def __init__(self, fun, *args, **kwargs):
- self.fun = fun
- self.pending = args[:]
- self.kwargs = kwargs.copy()
-
- def __call__(self, *args, **kwargs):
- if kwargs and self.kwargs:
- kw = self.kwargs.copy()
- kw.update(kwargs)
- else:
- kw = kwargs or self.kwargs
-
- return self.fun(*(self.pending + args), **kw)
-
-import types
-# Don't "from types import ..." these because we need to get at the
-# types module later to look for UnicodeType.
-DictType = types.DictType
-InstanceType = types.InstanceType
-ListType = types.ListType
-StringType = types.StringType
-TupleType = types.TupleType
-if hasattr(types, 'UnicodeType'):
- UnicodeType = types.UnicodeType
- def isstring(obj):
- t = type(obj)
- return t is StringType \
- or t is UnicodeType \
- or (t is InstanceType and isinstance(obj, UserString))
-else:
- def isstring(obj):
- t = type(obj)
- return t is StringType \
- or (t is InstanceType and isinstance(obj, UserString))
-
-if __name__ == '__main__':
- a1 = 'a.b.c'
- assert a1.split('.', -1) == a1.rsplit('.', -1) == _rsplit(a1, '.', -1)
-
- assert a1.rsplit('.', 1) == _rsplit(a1, '.', 1)
-
- assert a1.rsplit('.', 0) == _rsplit(a1, '.', 0)
-
- assert a1.rsplit('.', 2) == _rsplit(a1, '.', 2)
-
- a2 = 'floupi'
- assert a2.rsplit('.') == _rsplit(a2, '.', -1)
- assert a2.rsplit('.', 1) == _rsplit(a2, '.', 1)
More information about the Numpy-svn
mailing list