diff options
author | Tim Peters <tim.peters@gmail.com> | 2004-07-18 06:16:08 +0000 |
---|---|---|
committer | Tim Peters <tim.peters@gmail.com> | 2004-07-18 06:16:08 +0000 |
commit | c71fe97a2c07d09144fd634f442a8ad29c84e0c0 (patch) | |
tree | a3058fb9abd3146b5bafd435e449cce2df397876 /Tools/freeze | |
parent | acbad78022027cf7d94c4b9d60b1a1f44441ad93 (diff) | |
download | cpython-c71fe97a2c07d09144fd634f442a8ad29c84e0c0.tar.gz |
Whitespace normalization, via reindent.py.
Diffstat (limited to 'Tools/freeze')
-rw-r--r-- | Tools/freeze/bkfile.py | 82 | ||||
-rw-r--r-- | Tools/freeze/checkextensions.py | 146 | ||||
-rw-r--r-- | Tools/freeze/checkextensions_win32.py | 250 | ||||
-rwxr-xr-x | Tools/freeze/freeze.py | 12 | ||||
-rw-r--r-- | Tools/freeze/makeconfig.py | 92 | ||||
-rw-r--r-- | Tools/freeze/makefreeze.py | 2 | ||||
-rw-r--r-- | Tools/freeze/makemakefile.py | 2 | ||||
-rw-r--r-- | Tools/freeze/parsesetup.py | 162 |
8 files changed, 373 insertions, 375 deletions
diff --git a/Tools/freeze/bkfile.py b/Tools/freeze/bkfile.py index d29716a93c..54af2fac89 100644 --- a/Tools/freeze/bkfile.py +++ b/Tools/freeze/bkfile.py @@ -1,47 +1,47 @@ _orig_open = open class _BkFile: - def __init__(self, file, mode, bufsize): - import os - self.__filename = file - self.__backup = file + '~' - try: - os.unlink(self.__backup) - except os.error: - pass - try: - os.rename(file, self.__backup) - except os.error: - self.__backup = None - self.__file = _orig_open(file, mode, bufsize) - self.closed = self.__file.closed - self.fileno = self.__file.fileno - self.flush = self.__file.flush - self.isatty = self.__file.isatty - self.mode = self.__file.mode - self.name = self.__file.name - self.read = self.__file.read - self.readinto = self.__file.readinto - self.readline = self.__file.readline - self.readlines = self.__file.readlines - self.seek = self.__file.seek - self.softspace = self.__file.softspace - self.tell = self.__file.tell - self.truncate = self.__file.truncate - self.write = self.__file.write - self.writelines = self.__file.writelines + def __init__(self, file, mode, bufsize): + import os + self.__filename = file + self.__backup = file + '~' + try: + os.unlink(self.__backup) + except os.error: + pass + try: + os.rename(file, self.__backup) + except os.error: + self.__backup = None + self.__file = _orig_open(file, mode, bufsize) + self.closed = self.__file.closed + self.fileno = self.__file.fileno + self.flush = self.__file.flush + self.isatty = self.__file.isatty + self.mode = self.__file.mode + self.name = self.__file.name + self.read = self.__file.read + self.readinto = self.__file.readinto + self.readline = self.__file.readline + self.readlines = self.__file.readlines + self.seek = self.__file.seek + self.softspace = self.__file.softspace + self.tell = self.__file.tell + self.truncate = self.__file.truncate + self.write = self.__file.write + self.writelines = self.__file.writelines - def close(self): - self.__file.close() - if self.__backup is None: - return - import filecmp - if filecmp.cmp(self.__backup, self.__filename, shallow = 0): - import os - os.unlink(self.__filename) - os.rename(self.__backup, self.__filename) + def close(self): + self.__file.close() + if self.__backup is None: + return + import filecmp + if filecmp.cmp(self.__backup, self.__filename, shallow = 0): + import os + os.unlink(self.__filename) + os.rename(self.__backup, self.__filename) def open(file, mode = 'r', bufsize = -1): - if 'w' not in mode: - return _orig_open(file, mode, bufsize) - return _BkFile(file, mode, bufsize) + if 'w' not in mode: + return _orig_open(file, mode, bufsize) + return _BkFile(file, mode, bufsize) diff --git a/Tools/freeze/checkextensions.py b/Tools/freeze/checkextensions.py index 584f8a66db..334521f559 100644 --- a/Tools/freeze/checkextensions.py +++ b/Tools/freeze/checkextensions.py @@ -6,85 +6,85 @@ import os import parsesetup def checkextensions(unknown, extensions): - files = [] - modules = [] - edict = {} - for e in extensions: - setup = os.path.join(e, 'Setup') - liba = os.path.join(e, 'lib.a') - if not os.path.isfile(liba): - liba = None - edict[e] = parsesetup.getsetupinfo(setup), liba - for mod in unknown: - for e in extensions: - (mods, vars), liba = edict[e] - if not mods.has_key(mod): - continue - modules.append(mod) - if liba: - # If we find a lib.a, use it, ignore the - # .o files, and use *all* libraries for - # *all* modules in the Setup file - if liba in files: - break - files.append(liba) - for m in mods.keys(): - files = files + select(e, mods, vars, - m, 1) - break - files = files + select(e, mods, vars, mod, 0) - break - return files, modules + files = [] + modules = [] + edict = {} + for e in extensions: + setup = os.path.join(e, 'Setup') + liba = os.path.join(e, 'lib.a') + if not os.path.isfile(liba): + liba = None + edict[e] = parsesetup.getsetupinfo(setup), liba + for mod in unknown: + for e in extensions: + (mods, vars), liba = edict[e] + if not mods.has_key(mod): + continue + modules.append(mod) + if liba: + # If we find a lib.a, use it, ignore the + # .o files, and use *all* libraries for + # *all* modules in the Setup file + if liba in files: + break + files.append(liba) + for m in mods.keys(): + files = files + select(e, mods, vars, + m, 1) + break + files = files + select(e, mods, vars, mod, 0) + break + return files, modules def select(e, mods, vars, mod, skipofiles): - files = [] - for w in mods[mod]: - w = treatword(w) - if not w: - continue - w = expandvars(w, vars) - for w in w.split(): - if skipofiles and w[-2:] == '.o': - continue - # Assume $var expands to absolute pathname - if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'): - w = os.path.join(e, w) - if w[:2] in ('-L', '-R') and w[2:3] != '$': - w = w[:2] + os.path.join(e, w[2:]) - files.append(w) - return files + files = [] + for w in mods[mod]: + w = treatword(w) + if not w: + continue + w = expandvars(w, vars) + for w in w.split(): + if skipofiles and w[-2:] == '.o': + continue + # Assume $var expands to absolute pathname + if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'): + w = os.path.join(e, w) + if w[:2] in ('-L', '-R') and w[2:3] != '$': + w = w[:2] + os.path.join(e, w[2:]) + files.append(w) + return files cc_flags = ['-I', '-D', '-U'] cc_exts = ['.c', '.C', '.cc', '.c++'] def treatword(w): - if w[:2] in cc_flags: - return None - if w[:1] == '-': - return w # Assume loader flag - head, tail = os.path.split(w) - base, ext = os.path.splitext(tail) - if ext in cc_exts: - tail = base + '.o' - w = os.path.join(head, tail) - return w + if w[:2] in cc_flags: + return None + if w[:1] == '-': + return w # Assume loader flag + head, tail = os.path.split(w) + base, ext = os.path.splitext(tail) + if ext in cc_exts: + tail = base + '.o' + w = os.path.join(head, tail) + return w def expandvars(str, vars): - i = 0 - while i < len(str): - i = k = str.find('$', i) - if i < 0: - break - i = i+1 - var = str[i:i+1] - i = i+1 - if var == '(': - j = str.find(')', i) - if j < 0: - break - var = str[i:j] - i = j+1 - if vars.has_key(var): - str = str[:k] + vars[var] + str[i:] - i = k - return str + i = 0 + while i < len(str): + i = k = str.find('$', i) + if i < 0: + break + i = i+1 + var = str[i:i+1] + i = i+1 + if var == '(': + j = str.find(')', i) + if j < 0: + break + var = str[i:j] + i = j+1 + if vars.has_key(var): + str = str[:k] + vars[var] + str[i:] + i = k + return str diff --git a/Tools/freeze/checkextensions_win32.py b/Tools/freeze/checkextensions_win32.py index 9a7a6dccec..a198ecf39b 100644 --- a/Tools/freeze/checkextensions_win32.py +++ b/Tools/freeze/checkextensions_win32.py @@ -24,142 +24,142 @@ but an obvious enhancement would be to provide command line options. import os, sys try: - import win32api + import win32api except ImportError: - win32api = None # User has already been warned + win32api = None # User has already been warned class CExtension: - """An abstraction of an extension implemented in C/C++ - """ - def __init__(self, name, sourceFiles): - self.name = name - # A list of strings defining additional compiler options. - self.sourceFiles = sourceFiles - # A list of special compiler options to be applied to - # all source modules in this extension. - self.compilerOptions = [] - # A list of .lib files the final .EXE will need. - self.linkerLibs = [] - - def GetSourceFiles(self): - return self.sourceFiles - - def AddCompilerOption(self, option): - self.compilerOptions.append(option) - def GetCompilerOptions(self): - return self.compilerOptions - - def AddLinkerLib(self, lib): - self.linkerLibs.append(lib) - def GetLinkerLibs(self): - return self.linkerLibs + """An abstraction of an extension implemented in C/C++ + """ + def __init__(self, name, sourceFiles): + self.name = name + # A list of strings defining additional compiler options. + self.sourceFiles = sourceFiles + # A list of special compiler options to be applied to + # all source modules in this extension. + self.compilerOptions = [] + # A list of .lib files the final .EXE will need. + self.linkerLibs = [] + + def GetSourceFiles(self): + return self.sourceFiles + + def AddCompilerOption(self, option): + self.compilerOptions.append(option) + def GetCompilerOptions(self): + return self.compilerOptions + + def AddLinkerLib(self, lib): + self.linkerLibs.append(lib) + def GetLinkerLibs(self): + return self.linkerLibs def checkextensions(unknown, extra_inis, prefix): - # Create a table of frozen extensions - - defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini") - if not os.path.isfile(defaultMapName): - sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found\n" % defaultMapName) - else: - # must go on end, so other inis can override. - extra_inis.append(defaultMapName) - - ret = [] - for mod in unknown: - for ini in extra_inis: -# print "Looking for", mod, "in", win32api.GetFullPathName(ini),"...", - defn = get_extension_defn( mod, ini, prefix ) - if defn is not None: -# print "Yay - found it!" - ret.append( defn ) - break -# print "Nope!" - else: # For not broken! - sys.stderr.write("No definition of module %s in any specified map file.\n" % (mod)) - - return ret + # Create a table of frozen extensions + + defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini") + if not os.path.isfile(defaultMapName): + sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found\n" % defaultMapName) + else: + # must go on end, so other inis can override. + extra_inis.append(defaultMapName) + + ret = [] + for mod in unknown: + for ini in extra_inis: +# print "Looking for", mod, "in", win32api.GetFullPathName(ini),"...", + defn = get_extension_defn( mod, ini, prefix ) + if defn is not None: +# print "Yay - found it!" + ret.append( defn ) + break +# print "Nope!" + else: # For not broken! + sys.stderr.write("No definition of module %s in any specified map file.\n" % (mod)) + + return ret def get_extension_defn(moduleName, mapFileName, prefix): - if win32api is None: return None - os.environ['PYTHONPREFIX'] = prefix - dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName) - if dsp=="": - return None - - # We allow environment variables in the file name - dsp = win32api.ExpandEnvironmentStrings(dsp) - # If the path to the .DSP file is not absolute, assume it is relative - # to the description file. - if not os.path.isabs(dsp): - dsp = os.path.join( os.path.split(mapFileName)[0], dsp) - # Parse it to extract the source files. - sourceFiles = parse_dsp(dsp) - if sourceFiles is None: - return None - - module = CExtension(moduleName, sourceFiles) - # Put the path to the DSP into the environment so entries can reference it. - os.environ['dsp_path'] = os.path.split(dsp)[0] - os.environ['ini_path'] = os.path.split(mapFileName)[0] - - cl_options = win32api.GetProfileVal(moduleName, "cl", "", mapFileName) - if cl_options: - module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options)) - - exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName) - exclude = exclude.split() - - if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName): - module.AddCompilerOption('/D UNICODE /D _UNICODE') - - libs = win32api.GetProfileVal(moduleName, "libs", "", mapFileName).split() - for lib in libs: - module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib)) - - for exc in exclude: - if exc in module.sourceFiles: - modules.sourceFiles.remove(exc) - - return module + if win32api is None: return None + os.environ['PYTHONPREFIX'] = prefix + dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName) + if dsp=="": + return None + + # We allow environment variables in the file name + dsp = win32api.ExpandEnvironmentStrings(dsp) + # If the path to the .DSP file is not absolute, assume it is relative + # to the description file. + if not os.path.isabs(dsp): + dsp = os.path.join( os.path.split(mapFileName)[0], dsp) + # Parse it to extract the source files. + sourceFiles = parse_dsp(dsp) + if sourceFiles is None: + return None + + module = CExtension(moduleName, sourceFiles) + # Put the path to the DSP into the environment so entries can reference it. + os.environ['dsp_path'] = os.path.split(dsp)[0] + os.environ['ini_path'] = os.path.split(mapFileName)[0] + + cl_options = win32api.GetProfileVal(moduleName, "cl", "", mapFileName) + if cl_options: + module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options)) + + exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName) + exclude = exclude.split() + + if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName): + module.AddCompilerOption('/D UNICODE /D _UNICODE') + + libs = win32api.GetProfileVal(moduleName, "libs", "", mapFileName).split() + for lib in libs: + module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib)) + + for exc in exclude: + if exc in module.sourceFiles: + modules.sourceFiles.remove(exc) + + return module # Given an MSVC DSP file, locate C source files it uses # returns a list of source files. def parse_dsp(dsp): -# print "Processing", dsp - # For now, only support - ret = [] - dsp_path, dsp_name = os.path.split(dsp) - try: - lines = open(dsp, "r").readlines() - except IOError, msg: - sys.stderr.write("%s: %s\n" % (dsp, msg)) - return None - for line in lines: - fields = line.strip().split("=", 2) - if fields[0]=="SOURCE": - if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']: - ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) ) - return ret +# print "Processing", dsp + # For now, only support + ret = [] + dsp_path, dsp_name = os.path.split(dsp) + try: + lines = open(dsp, "r").readlines() + except IOError, msg: + sys.stderr.write("%s: %s\n" % (dsp, msg)) + return None + for line in lines: + fields = line.strip().split("=", 2) + if fields[0]=="SOURCE": + if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']: + ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) ) + return ret def write_extension_table(fname, modules): - fp = open(fname, "w") - try: - fp.write (ext_src_header) - # Write fn protos - for module in modules: - # bit of a hack for .pyd's as part of packages. - name = module.name.split('.')[-1] - fp.write('extern void init%s(void);\n' % (name) ) - # Write the table - fp.write (ext_tab_header) - for module in modules: - name = module.name.split('.')[-1] - fp.write('\t{"%s", init%s},\n' % (name, name) ) - - fp.write (ext_tab_footer) - fp.write(ext_src_footer) - finally: - fp.close() + fp = open(fname, "w") + try: + fp.write (ext_src_header) + # Write fn protos + for module in modules: + # bit of a hack for .pyd's as part of packages. + name = module.name.split('.')[-1] + fp.write('extern void init%s(void);\n' % (name) ) + # Write the table + fp.write (ext_tab_header) + for module in modules: + name = module.name.split('.')[-1] + fp.write('\t{"%s", init%s},\n' % (name, name) ) + + fp.write (ext_tab_footer) + fp.write(ext_src_footer) + finally: + fp.close() ext_src_header = """\ @@ -182,9 +182,7 @@ extern DL_IMPORT(int) PyImport_ExtendInittab(struct _inittab *newtab); int PyInitFrozenExtensions() { - return PyImport_ExtendInittab(extensions); + return PyImport_ExtendInittab(extensions); } """ - - diff --git a/Tools/freeze/freeze.py b/Tools/freeze/freeze.py index c2c3c2e14d..836f53261f 100755 --- a/Tools/freeze/freeze.py +++ b/Tools/freeze/freeze.py @@ -57,15 +57,15 @@ Options: are read and the -i option replaced with the parsed params (note - quoting args in this file is NOT supported) --s subsystem: Specify the subsystem (For Windows only.); +-s subsystem: Specify the subsystem (For Windows only.); 'console' (default), 'windows', 'service' or 'com_dll' - + -w: Toggle Windows (NT or 95) behavior. (For debugging only -- on a win32 platform, win32 behavior is automatic.) -r prefix=f: Replace path prefix. - Replace prefix with f in the source path references + Replace prefix with f in the source path references contained in the resulting binary. Arguments: @@ -335,7 +335,7 @@ def main(): winmakemakefile.get_custom_entry_point(subsystem) except ValueError, why: usage(why) - + # Actual work starts here... @@ -343,7 +343,7 @@ def main(): dir = os.path.dirname(scriptfile) path[0] = dir mf = modulefinder.ModuleFinder(path, debug, exclude, replace_paths) - + if win and subsystem=='service': # If a Windows service, then add the "built-in" module. mod = mf.add_module("servicemanager") @@ -411,7 +411,7 @@ def main(): else: # Do the windows thang... import checkextensions_win32 - # Get a list of CExtension instances, each describing a module + # Get a list of CExtension instances, each describing a module # (including its source files) frozen_extensions = checkextensions_win32.checkextensions( unknown, extensions, prefix) diff --git a/Tools/freeze/makeconfig.py b/Tools/freeze/makeconfig.py index 2f04ac7f57..7cd9b78478 100644 --- a/Tools/freeze/makeconfig.py +++ b/Tools/freeze/makeconfig.py @@ -6,56 +6,56 @@ import re never = ['marshal', '__main__', '__builtin__', 'sys', 'exceptions'] def makeconfig(infp, outfp, modules, with_ifdef=0): - m1 = re.compile('-- ADDMODULE MARKER 1 --') - m2 = re.compile('-- ADDMODULE MARKER 2 --') - while 1: - line = infp.readline() - if not line: break - outfp.write(line) - if m1 and m1.search(line): - m1 = None - for mod in modules: - if mod in never: - continue - if with_ifdef: - outfp.write("#ifndef init%s\n"%mod) - outfp.write('extern void init%s(void);\n' % mod) - if with_ifdef: - outfp.write("#endif\n") - elif m2 and m2.search(line): - m2 = None - for mod in modules: - if mod in never: - continue - outfp.write('\t{"%s", init%s},\n' % - (mod, mod)) - if m1: - sys.stderr.write('MARKER 1 never found\n') - elif m2: - sys.stderr.write('MARKER 2 never found\n') + m1 = re.compile('-- ADDMODULE MARKER 1 --') + m2 = re.compile('-- ADDMODULE MARKER 2 --') + while 1: + line = infp.readline() + if not line: break + outfp.write(line) + if m1 and m1.search(line): + m1 = None + for mod in modules: + if mod in never: + continue + if with_ifdef: + outfp.write("#ifndef init%s\n"%mod) + outfp.write('extern void init%s(void);\n' % mod) + if with_ifdef: + outfp.write("#endif\n") + elif m2 and m2.search(line): + m2 = None + for mod in modules: + if mod in never: + continue + outfp.write('\t{"%s", init%s},\n' % + (mod, mod)) + if m1: + sys.stderr.write('MARKER 1 never found\n') + elif m2: + sys.stderr.write('MARKER 2 never found\n') # Test program. def test(): - import sys - if not sys.argv[3:]: - print 'usage: python makeconfig.py config.c.in outputfile', - print 'modulename ...' - sys.exit(2) - if sys.argv[1] == '-': - infp = sys.stdin - else: - infp = open(sys.argv[1]) - if sys.argv[2] == '-': - outfp = sys.stdout - else: - outfp = open(sys.argv[2], 'w') - makeconfig(infp, outfp, sys.argv[3:]) - if outfp != sys.stdout: - outfp.close() - if infp != sys.stdin: - infp.close() + import sys + if not sys.argv[3:]: + print 'usage: python makeconfig.py config.c.in outputfile', + print 'modulename ...' + sys.exit(2) + if sys.argv[1] == '-': + infp = sys.stdin + else: + infp = open(sys.argv[1]) + if sys.argv[2] == '-': + outfp = sys.stdout + else: + outfp = open(sys.argv[2], 'w') + makeconfig(infp, outfp, sys.argv[3:]) + if outfp != sys.stdout: + outfp.close() + if infp != sys.stdin: + infp.close() if __name__ == '__main__': - test() + test() diff --git a/Tools/freeze/makefreeze.py b/Tools/freeze/makefreeze.py index 9ff348c59a..1208b67fe0 100644 --- a/Tools/freeze/makefreeze.py +++ b/Tools/freeze/makefreeze.py @@ -19,7 +19,7 @@ default_entry_point = """ int main(int argc, char **argv) { - extern int Py_FrozenMain(int, char **); + extern int Py_FrozenMain(int, char **); """ + ((not __debug__ and """ Py_OptimizeFlag++; """) or "") + """ diff --git a/Tools/freeze/makemakefile.py b/Tools/freeze/makemakefile.py index b8b99b8768..ff8b15a199 100644 --- a/Tools/freeze/makemakefile.py +++ b/Tools/freeze/makemakefile.py @@ -23,7 +23,7 @@ def makemakefile(outfp, makevars, files, target): deps.append(dest) outfp.write("\n%s: %s\n" % (target, ' '.join(deps))) - outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" % + outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" % (' '.join(files), target)) outfp.write("\nclean:\n\t-rm -f *.o %s\n" % target) diff --git a/Tools/freeze/parsesetup.py b/Tools/freeze/parsesetup.py index 2b9123ea4d..856234d443 100644 --- a/Tools/freeze/parsesetup.py +++ b/Tools/freeze/parsesetup.py @@ -10,32 +10,32 @@ import re makevardef = re.compile('^([a-zA-Z0-9_]+)[ \t]*=(.*)') def getmakevars(filename): - variables = {} - fp = open(filename) - pendingline = "" - try: - while 1: - line = fp.readline() - if pendingline: - line = pendingline + line - pendingline = "" - if not line: - break - if line.endswith('\\\n'): - pendingline = line[:-2] - matchobj = makevardef.match(line) - if not matchobj: - continue - (name, value) = matchobj.group(1, 2) - # Strip trailing comment - i = value.find('#') - if i >= 0: - value = value[:i] - value = value.strip() - variables[name] = value - finally: - fp.close() - return variables + variables = {} + fp = open(filename) + pendingline = "" + try: + while 1: + line = fp.readline() + if pendingline: + line = pendingline + line + pendingline = "" + if not line: + break + if line.endswith('\\\n'): + pendingline = line[:-2] + matchobj = makevardef.match(line) + if not matchobj: + continue + (name, value) = matchobj.group(1, 2) + # Strip trailing comment + i = value.find('#') + if i >= 0: + value = value[:i] + value = value.strip() + variables[name] = value + finally: + fp.close() + return variables # Parse a Python Setup(.in) file. @@ -46,67 +46,67 @@ def getmakevars(filename): setupvardef = re.compile('^([a-zA-Z0-9_]+)=(.*)') def getsetupinfo(filename): - modules = {} - variables = {} - fp = open(filename) - pendingline = "" - try: - while 1: - line = fp.readline() - if pendingline: - line = pendingline + line - pendingline = "" - if not line: - break - # Strip comments - i = line.find('#') - if i >= 0: - line = line[:i] - if line.endswith('\\\n'): - pendingline = line[:-2] - continue - matchobj = setupvardef.match(line) - if matchobj: - (name, value) = matchobj.group(1, 2) - variables[name] = value.strip() - else: - words = line.split() - if words: - modules[words[0]] = words[1:] - finally: - fp.close() - return modules, variables + modules = {} + variables = {} + fp = open(filename) + pendingline = "" + try: + while 1: + line = fp.readline() + if pendingline: + line = pendingline + line + pendingline = "" + if not line: + break + # Strip comments + i = line.find('#') + if i >= 0: + line = line[:i] + if line.endswith('\\\n'): + pendingline = line[:-2] + continue + matchobj = setupvardef.match(line) + if matchobj: + (name, value) = matchobj.group(1, 2) + variables[name] = value.strip() + else: + words = line.split() + if words: + modules[words[0]] = words[1:] + finally: + fp.close() + return modules, variables # Test the above functions. def test(): - import sys - import os - if not sys.argv[1:]: - print 'usage: python parsesetup.py Makefile*|Setup* ...' - sys.exit(2) - for arg in sys.argv[1:]: - base = os.path.basename(arg) - if base[:8] == 'Makefile': - print 'Make style parsing:', arg - v = getmakevars(arg) - prdict(v) - elif base[:5] == 'Setup': - print 'Setup style parsing:', arg - m, v = getsetupinfo(arg) - prdict(m) - prdict(v) - else: - print arg, 'is neither a Makefile nor a Setup file' - print '(name must begin with "Makefile" or "Setup")' + import sys + import os + if not sys.argv[1:]: + print 'usage: python parsesetup.py Makefile*|Setup* ...' + sys.exit(2) + for arg in sys.argv[1:]: + base = os.path.basename(arg) + if base[:8] == 'Makefile': + print 'Make style parsing:', arg + v = getmakevars(arg) + prdict(v) + elif base[:5] == 'Setup': + print 'Setup style parsing:', arg + m, v = getsetupinfo(arg) + prdict(m) + prdict(v) + else: + print arg, 'is neither a Makefile nor a Setup file' + print '(name must begin with "Makefile" or "Setup")' def prdict(d): - keys = d.keys() - keys.sort() - for key in keys: - value = d[key] - print "%-15s" % key, str(value) + keys = d.keys() + keys.sort() + for key in keys: + value = d[key] + print "%-15s" % key, str(value) if __name__ == '__main__': - test() + test() |