diff options
author | Tim Peters <tim.peters@gmail.com> | 2001-01-15 03:26:36 (GMT) |
---|---|---|
committer | Tim Peters <tim.peters@gmail.com> | 2001-01-15 03:26:36 (GMT) |
commit | b90f89a496676ec714e111a747344600f3988496 (patch) | |
tree | 161c61762992b5c1588c9a49f557ad88b31b091f /Lib | |
parent | 495ad3c8ccb9ed3554177a3e8687676c78e667de (diff) | |
download | cpython-b90f89a496676ec714e111a747344600f3988496.zip cpython-b90f89a496676ec714e111a747344600f3988496.tar.gz cpython-b90f89a496676ec714e111a747344600f3988496.tar.bz2 |
Whitespace normalization.
Diffstat (limited to 'Lib')
-rwxr-xr-x | Lib/tabnanny.py | 233 | ||||
-rw-r--r-- | Lib/telnetlib.py | 6 | ||||
-rw-r--r-- | Lib/tempfile.py | 50 | ||||
-rw-r--r-- | Lib/threading.py | 6 | ||||
-rw-r--r-- | Lib/toaiff.py | 88 | ||||
-rw-r--r-- | Lib/tokenize.py | 1 | ||||
-rw-r--r-- | Lib/traceback.py | 466 | ||||
-rw-r--r-- | Lib/tty.py | 35 | ||||
-rw-r--r-- | Lib/tzparse.py | 142 |
9 files changed, 512 insertions, 515 deletions
diff --git a/Lib/tabnanny.py b/Lib/tabnanny.py index 8d3eab5..ea4fbc6 100755 --- a/Lib/tabnanny.py +++ b/Lib/tabnanny.py @@ -248,125 +248,124 @@ def format_witnesses(w): # in use. if hasattr(tokenize, 'NL'): - # take advantage of Guido's patch! - - indents = [] - check_equal = 0 - - def reset_globals(): - global indents, check_equal - check_equal = 0 - indents = [Whitespace("")] - - def tokeneater(type, token, start, end, line, - INDENT=tokenize.INDENT, - DEDENT=tokenize.DEDENT, - NEWLINE=tokenize.NEWLINE, - JUNK=(tokenize.COMMENT, tokenize.NL) ): - global indents, check_equal - - if type == NEWLINE: - # a program statement, or ENDMARKER, will eventually follow, - # after some (possibly empty) run of tokens of the form - # (NL | COMMENT)* (INDENT | DEDENT+)? - # If an INDENT appears, setting check_equal is wrong, and will - # be undone when we see the INDENT. - check_equal = 1 - - elif type == INDENT: - check_equal = 0 - thisguy = Whitespace(token) - if not indents[-1].less(thisguy): - witness = indents[-1].not_less_witness(thisguy) - msg = "indent not greater e.g. " + format_witnesses(witness) - raise NannyNag(start[0], msg, line) - indents.append(thisguy) - - elif type == DEDENT: - # there's nothing we need to check here! what's important is - # that when the run of DEDENTs ends, the indentation of the - # program statement (or ENDMARKER) that triggered the run is - # equal to what's left at the top of the indents stack - - # Ouch! This assert triggers if the last line of the source - # is indented *and* lacks a newline -- then DEDENTs pop out - # of thin air. - # assert check_equal # else no earlier NEWLINE, or an earlier INDENT - check_equal = 1 - - del indents[-1] - - elif check_equal and type not in JUNK: - # this is the first "real token" following a NEWLINE, so it - # must be the first token of the next program statement, or an - # ENDMARKER; the "line" argument exposes the leading whitespace - # for this statement; in the case of ENDMARKER, line is an empty - # string, so will properly match the empty string with which the - # "indents" stack was seeded - check_equal = 0 - thisguy = Whitespace(line) - if not indents[-1].equal(thisguy): - witness = indents[-1].not_equal_witness(thisguy) - msg = "indent not equal e.g. " + format_witnesses(witness) - raise NannyNag(start[0], msg, line) + # take advantage of Guido's patch! + + indents = [] + check_equal = 0 + + def reset_globals(): + global indents, check_equal + check_equal = 0 + indents = [Whitespace("")] + + def tokeneater(type, token, start, end, line, + INDENT=tokenize.INDENT, + DEDENT=tokenize.DEDENT, + NEWLINE=tokenize.NEWLINE, + JUNK=(tokenize.COMMENT, tokenize.NL) ): + global indents, check_equal + + if type == NEWLINE: + # a program statement, or ENDMARKER, will eventually follow, + # after some (possibly empty) run of tokens of the form + # (NL | COMMENT)* (INDENT | DEDENT+)? + # If an INDENT appears, setting check_equal is wrong, and will + # be undone when we see the INDENT. + check_equal = 1 + + elif type == INDENT: + check_equal = 0 + thisguy = Whitespace(token) + if not indents[-1].less(thisguy): + witness = indents[-1].not_less_witness(thisguy) + msg = "indent not greater e.g. " + format_witnesses(witness) + raise NannyNag(start[0], msg, line) + indents.append(thisguy) + + elif type == DEDENT: + # there's nothing we need to check here! what's important is + # that when the run of DEDENTs ends, the indentation of the + # program statement (or ENDMARKER) that triggered the run is + # equal to what's left at the top of the indents stack + + # Ouch! This assert triggers if the last line of the source + # is indented *and* lacks a newline -- then DEDENTs pop out + # of thin air. + # assert check_equal # else no earlier NEWLINE, or an earlier INDENT + check_equal = 1 + + del indents[-1] + + elif check_equal and type not in JUNK: + # this is the first "real token" following a NEWLINE, so it + # must be the first token of the next program statement, or an + # ENDMARKER; the "line" argument exposes the leading whitespace + # for this statement; in the case of ENDMARKER, line is an empty + # string, so will properly match the empty string with which the + # "indents" stack was seeded + check_equal = 0 + thisguy = Whitespace(line) + if not indents[-1].equal(thisguy): + witness = indents[-1].not_equal_witness(thisguy) + msg = "indent not equal e.g. " + format_witnesses(witness) + raise NannyNag(start[0], msg, line) else: - # unpatched version of tokenize - - nesting_level = 0 - indents = [] - check_equal = 0 - - def reset_globals(): - global nesting_level, indents, check_equal - nesting_level = check_equal = 0 - indents = [Whitespace("")] - - def tokeneater(type, token, start, end, line, - INDENT=tokenize.INDENT, - DEDENT=tokenize.DEDENT, - NEWLINE=tokenize.NEWLINE, - COMMENT=tokenize.COMMENT, - OP=tokenize.OP): - global nesting_level, indents, check_equal - - if type == INDENT: - check_equal = 0 - thisguy = Whitespace(token) - if not indents[-1].less(thisguy): - witness = indents[-1].not_less_witness(thisguy) - msg = "indent not greater e.g. " + format_witnesses(witness) - raise NannyNag(start[0], msg, line) - indents.append(thisguy) - - elif type == DEDENT: - del indents[-1] - - elif type == NEWLINE: - if nesting_level == 0: - check_equal = 1 - - elif type == COMMENT: - pass - - elif check_equal: - check_equal = 0 - thisguy = Whitespace(line) - if not indents[-1].equal(thisguy): - witness = indents[-1].not_equal_witness(thisguy) - msg = "indent not equal e.g. " + format_witnesses(witness) - raise NannyNag(start[0], msg, line) - - if type == OP and token in ('{', '[', '('): - nesting_level = nesting_level + 1 - - elif type == OP and token in ('}', ']', ')'): - if nesting_level == 0: - raise NannyNag(start[0], - "unbalanced bracket '" + token + "'", - line) - nesting_level = nesting_level - 1 + # unpatched version of tokenize + + nesting_level = 0 + indents = [] + check_equal = 0 + + def reset_globals(): + global nesting_level, indents, check_equal + nesting_level = check_equal = 0 + indents = [Whitespace("")] + + def tokeneater(type, token, start, end, line, + INDENT=tokenize.INDENT, + DEDENT=tokenize.DEDENT, + NEWLINE=tokenize.NEWLINE, + COMMENT=tokenize.COMMENT, + OP=tokenize.OP): + global nesting_level, indents, check_equal + + if type == INDENT: + check_equal = 0 + thisguy = Whitespace(token) + if not indents[-1].less(thisguy): + witness = indents[-1].not_less_witness(thisguy) + msg = "indent not greater e.g. " + format_witnesses(witness) + raise NannyNag(start[0], msg, line) + indents.append(thisguy) + + elif type == DEDENT: + del indents[-1] + + elif type == NEWLINE: + if nesting_level == 0: + check_equal = 1 + + elif type == COMMENT: + pass + + elif check_equal: + check_equal = 0 + thisguy = Whitespace(line) + if not indents[-1].equal(thisguy): + witness = indents[-1].not_equal_witness(thisguy) + msg = "indent not equal e.g. " + format_witnesses(witness) + raise NannyNag(start[0], msg, line) + + if type == OP and token in ('{', '[', '('): + nesting_level = nesting_level + 1 + + elif type == OP and token in ('}', ']', ')'): + if nesting_level == 0: + raise NannyNag(start[0], + "unbalanced bracket '" + token + "'", + line) + nesting_level = nesting_level - 1 if __name__ == '__main__': main() - diff --git a/Lib/telnetlib.py b/Lib/telnetlib.py index dfd549e..d2d0b9b 100644 --- a/Lib/telnetlib.py +++ b/Lib/telnetlib.py @@ -11,7 +11,7 @@ Example: >>> print tn.read_all() Login Name TTY Idle When Where guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston.. - + >>> Note that read_all() won't read until eof -- it just reads some data @@ -250,7 +250,7 @@ class Telnet: def read_very_eager(self): """Read everything that's possible without blocking in I/O (eager). - + Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. @@ -278,7 +278,7 @@ class Telnet: def read_lazy(self): """Process and return data that's already in the queues (lazy). - + Raise EOFError if connection closed and no data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 8ac707d..a503e7f 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -26,10 +26,10 @@ def gettempdir(): elif os.name == 'mac': import macfs, MACFS try: - refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, - MACFS.kTemporaryFolderType, 1) - dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() - attempdirs.insert(0, dirname) + refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk, + MACFS.kTemporaryFolderType, 1) + dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname() + attempdirs.insert(0, dirname) except macfs.error: pass for envname in 'TMPDIR', 'TEMP', 'TMP': @@ -38,27 +38,27 @@ def gettempdir(): testfile = gettempprefix() + 'test' for dir in attempdirs: try: - filename = os.path.join(dir, testfile) - if os.name == 'posix': - try: - fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700) - except OSError: - pass - else: - fp = os.fdopen(fd, 'w') - fp.write('blat') - fp.close() - os.unlink(filename) - del fp, fd - tempdir = dir - break - else: - fp = open(filename, 'w') - fp.write('blat') - fp.close() - os.unlink(filename) - tempdir = dir - break + filename = os.path.join(dir, testfile) + if os.name == 'posix': + try: + fd = os.open(filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700) + except OSError: + pass + else: + fp = os.fdopen(fd, 'w') + fp.write('blat') + fp.close() + os.unlink(filename) + del fp, fd + tempdir = dir + break + else: + fp = open(filename, 'w') + fp.write('blat') + fp.close() + os.unlink(filename) + tempdir = dir + break except IOError: pass if tempdir is None: diff --git a/Lib/threading.py b/Lib/threading.py index fbc1f5c..e484521 100644 --- a/Lib/threading.py +++ b/Lib/threading.py @@ -65,7 +65,7 @@ def RLock(*args, **kwargs): return apply(_RLock, args, kwargs) class _RLock(_Verbose): - + def __init__(self, verbose=None): _Verbose.__init__(self, verbose) self.__block = _allocate_lock() @@ -440,7 +440,7 @@ class Thread(_Verbose): def isAlive(self): assert self.__initialized, "Thread.__init__() not called" return self.__started and not self.__stopped - + def isDaemon(self): assert self.__initialized, "Thread.__init__() not called" return self.__daemonic @@ -496,7 +496,7 @@ def _pickSomeNonDaemonThread(): # when we exit (conform previous semantics). class _DummyThread(Thread): - + def __init__(self): Thread.__init__(self, name=_newname("Dummy-%d")) self._Thread__started = 1 diff --git a/Lib/toaiff.py b/Lib/toaiff.py index 25be46f..96d4642 100644 --- a/Lib/toaiff.py +++ b/Lib/toaiff.py @@ -54,51 +54,51 @@ uncompress.append('uncompress', '--') class error(Exception): - pass + pass def toaiff(filename): - temps = [] - ret = None - try: - ret = _toaiff(filename, temps) - finally: - for temp in temps[:]: - if temp != ret: - try: - os.unlink(temp) - except os.error: - pass - temps.remove(temp) - return ret + temps = [] + ret = None + try: + ret = _toaiff(filename, temps) + finally: + for temp in temps[:]: + if temp != ret: + try: + os.unlink(temp) + except os.error: + pass + temps.remove(temp) + return ret def _toaiff(filename, temps): - if filename[-2:] == '.Z': - fname = tempfile.mktemp() - temps.append(fname) - sts = uncompress.copy(filename, fname) - if sts: - raise error, filename + ': uncompress failed' - else: - fname = filename - try: - ftype = sndhdr.whathdr(fname) - if ftype: - ftype = ftype[0] # All we're interested in - except IOError: - if type(msg) == type(()) and len(msg) == 2 and \ - type(msg[0]) == type(0) and type(msg[1]) == type(''): - msg = msg[1] - if type(msg) != type(''): - msg = `msg` - raise error, filename + ': ' + msg - if ftype == 'aiff': - return fname - if ftype is None or not table.has_key(ftype): - raise error, \ - filename + ': unsupported audio file type ' + `ftype` - temp = tempfile.mktemp() - temps.append(temp) - sts = table[ftype].copy(fname, temp) - if sts: - raise error, filename + ': conversion to aiff failed' - return temp + if filename[-2:] == '.Z': + fname = tempfile.mktemp() + temps.append(fname) + sts = uncompress.copy(filename, fname) + if sts: + raise error, filename + ': uncompress failed' + else: + fname = filename + try: + ftype = sndhdr.whathdr(fname) + if ftype: + ftype = ftype[0] # All we're interested in + except IOError: + if type(msg) == type(()) and len(msg) == 2 and \ + type(msg[0]) == type(0) and type(msg[1]) == type(''): + msg = msg[1] + if type(msg) != type(''): + msg = `msg` + raise error, filename + ': ' + msg + if ftype == 'aiff': + return fname + if ftype is None or not table.has_key(ftype): + raise error, \ + filename + ': unsupported audio file type ' + `ftype` + temp = tempfile.mktemp() + temps.append(temp) + sts = table[ftype].copy(fname, temp) + if sts: + raise error, filename + ': conversion to aiff failed' + return temp diff --git a/Lib/tokenize.py b/Lib/tokenize.py index f2ba0a2..d205159 100644 --- a/Lib/tokenize.py +++ b/Lib/tokenize.py @@ -215,4 +215,3 @@ if __name__ == '__main__': # testing import sys if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) else: tokenize(sys.stdin.readline) - diff --git a/Lib/traceback.py b/Lib/traceback.py index 064712e..7097b8f 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -6,273 +6,273 @@ import sys import types def _print(file, str='', terminator='\n'): - file.write(str+terminator) + file.write(str+terminator) def print_list(extracted_list, file=None): - """Print the list of tuples as returned by extract_tb() or - extract_stack() as a formatted stack trace to the given file.""" - if not file: - file = sys.stderr - for filename, lineno, name, line in extracted_list: - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - if line: - _print(file, ' %s' % string.strip(line)) + """Print the list of tuples as returned by extract_tb() or + extract_stack() as a formatted stack trace to the given file.""" + if not file: + file = sys.stderr + for filename, lineno, name, line in extracted_list: + _print(file, + ' File "%s", line %d, in %s' % (filename,lineno,name)) + if line: + _print(file, ' %s' % string.strip(line)) def format_list(extracted_list): - """Given a list of tuples as returned by extract_tb() or - extract_stack(), return a list of strings ready for printing. - Each string in the resulting list corresponds to the item with - the same index in the argument list. Each string ends in a - newline; the strings may contain internal newlines as well, for - those items whose source text line is not None.""" - list = [] - for filename, lineno, name, line in extracted_list: - item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) - if line: - item = item + ' %s\n' % string.strip(line) - list.append(item) - return list - + """Given a list of tuples as returned by extract_tb() or + extract_stack(), return a list of strings ready for printing. + Each string in the resulting list corresponds to the item with + the same index in the argument list. Each string ends in a + newline; the strings may contain internal newlines as well, for + those items whose source text line is not None.""" + list = [] + for filename, lineno, name, line in extracted_list: + item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) + if line: + item = item + ' %s\n' % string.strip(line) + list.append(item) + return list + def print_tb(tb, limit=None, file=None): - """Print up to 'limit' stack trace entries from the traceback 'tb'. - If 'limit' is omitted or None, all entries are printed. If 'file' is - omitted or None, the output goes to sys.stderr; otherwise 'file' - should be an open file or file-like object with a write() method.""" - if not file: - file = sys.stderr - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb_lineno(tb) - co = f.f_code - filename = co.co_filename - name = co.co_name - _print(file, - ' File "%s", line %d, in %s' % (filename,lineno,name)) - line = linecache.getline(filename, lineno) - if line: _print(file, ' ' + string.strip(line)) - tb = tb.tb_next - n = n+1 + """Print up to 'limit' stack trace entries from the traceback 'tb'. + If 'limit' is omitted or None, all entries are printed. If 'file' is + omitted or None, the output goes to sys.stderr; otherwise 'file' + should be an open file or file-like object with a write() method.""" + if not file: + file = sys.stderr + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb_lineno(tb) + co = f.f_code + filename = co.co_filename + name = co.co_name + _print(file, + ' File "%s", line %d, in %s' % (filename,lineno,name)) + line = linecache.getline(filename, lineno) + if line: _print(file, ' ' + string.strip(line)) + tb = tb.tb_next + n = n+1 def format_tb(tb, limit = None): - """A shorthand for 'format_list(extract_stack(f, limit)).""" - return format_list(extract_tb(tb, limit)) + """A shorthand for 'format_list(extract_stack(f, limit)).""" + return format_list(extract_tb(tb, limit)) def extract_tb(tb, limit = None): - """Return a list of up to 'limit' pre-processed stack trace entries - extracted from the traceback object 'traceback'. This is useful for - alternate formatting of stack traces. If 'limit' is omitted or None, - all entries are extracted. A pre-processed stack trace entry is a - quadruple (filename, line number, function name, text) representing - the information that is usually printed for a stack trace. The text - is a string with leading and trailing whitespace stripped; if the - source is not available it is None.""" - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while tb is not None and (limit is None or n < limit): - f = tb.tb_frame - lineno = tb_lineno(tb) - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = string.strip(line) - else: line = None - list.append((filename, lineno, name, line)) - tb = tb.tb_next - n = n+1 - return list + """Return a list of up to 'limit' pre-processed stack trace entries + extracted from the traceback object 'traceback'. This is useful for + alternate formatting of stack traces. If 'limit' is omitted or None, + all entries are extracted. A pre-processed stack trace entry is a + quadruple (filename, line number, function name, text) representing + the information that is usually printed for a stack trace. The text + is a string with leading and trailing whitespace stripped; if the + source is not available it is None.""" + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + list = [] + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb_lineno(tb) + co = f.f_code + filename = co.co_filename + name = co.co_name + line = linecache.getline(filename, lineno) + if line: line = string.strip(line) + else: line = None + list.append((filename, lineno, name, line)) + tb = tb.tb_next + n = n+1 + return list def print_exception(etype, value, tb, limit=None, file=None): - """Print exception information and up to 'limit' stack trace entries - from the traceback 'tb' to 'file'. This differs from print_tb() in - the following ways: (1) if traceback is not None, it prints a header - "Traceback (most recent call last):"; (2) it prints the exception type and - value after the stack trace; (3) if type is SyntaxError and value has - the appropriate format, it prints the line where the syntax error - occurred with a caret on the next line indicating the approximate - position of the error.""" - if not file: - file = sys.stderr - if tb: - _print(file, 'Traceback (most recent call last):') - print_tb(tb, limit, file) - lines = format_exception_only(etype, value) - for line in lines[:-1]: - _print(file, line, ' ') - _print(file, lines[-1], '') + """Print exception information and up to 'limit' stack trace entries + from the traceback 'tb' to 'file'. This differs from print_tb() in + the following ways: (1) if traceback is not None, it prints a header + "Traceback (most recent call last):"; (2) it prints the exception type and + value after the stack trace; (3) if type is SyntaxError and value has + the appropriate format, it prints the line where the syntax error + occurred with a caret on the next line indicating the approximate + position of the error.""" + if not file: + file = sys.stderr + if tb: + _print(file, 'Traceback (most recent call last):') + print_tb(tb, limit, file) + lines = format_exception_only(etype, value) + for line in lines[:-1]: + _print(file, line, ' ') + _print(file, lines[-1], '') def format_exception(etype, value, tb, limit = None): - """Format a stack trace and the exception information. The arguments - have the same meaning as the corresponding arguments to - print_exception(). The return value is a list of strings, each - ending in a newline and some containing internal newlines. When - these lines are concatenated and printed, exactly the same text is - printed as does print_exception().""" - if tb: - list = ['Traceback (most recent call last):\n'] - list = list + format_tb(tb, limit) - else: - list = [] - list = list + format_exception_only(etype, value) - return list + """Format a stack trace and the exception information. The arguments + have the same meaning as the corresponding arguments to + print_exception(). The return value is a list of strings, each + ending in a newline and some containing internal newlines. When + these lines are concatenated and printed, exactly the same text is + printed as does print_exception().""" + if tb: + list = ['Traceback (most recent call last):\n'] + list = list + format_tb(tb, limit) + else: + list = [] + list = list + format_exception_only(etype, value) + return list def format_exception_only(etype, value): - """Format the exception part of a traceback. The arguments are the - exception type and value such as given by sys.last_type and - sys.last_value. The return value is a list of strings, each ending - in a newline. Normally, the list contains a single string; - however, for SyntaxError exceptions, it contains several lines that - (when printed) display detailed information about where the syntax - error occurred. The message indicating which exception occurred is - the always last string in the list.""" - list = [] - if type(etype) == types.ClassType: - stype = etype.__name__ - else: - stype = etype - if value is None: - list.append(str(stype) + '\n') - else: - if etype is SyntaxError: - try: - msg, (filename, lineno, offset, line) = value - except: - pass - else: - if not filename: filename = "<string>" - list.append(' File "%s", line %d\n' % - (filename, lineno)) - i = 0 - while i < len(line) and \ - line[i] in string.whitespace: - i = i+1 - list.append(' %s\n' % string.strip(line)) - s = ' ' - for c in line[i:offset-1]: - if c in string.whitespace: - s = s + c - else: - s = s + ' ' - list.append('%s^\n' % s) - value = msg - s = _some_str(value) - if s: - list.append('%s: %s\n' % (str(stype), s)) - else: - list.append('%s\n' % str(stype)) - return list + """Format the exception part of a traceback. The arguments are the + exception type and value such as given by sys.last_type and + sys.last_value. The return value is a list of strings, each ending + in a newline. Normally, the list contains a single string; + however, for SyntaxError exceptions, it contains several lines that + (when printed) display detailed information about where the syntax + error occurred. The message indicating which exception occurred is + the always last string in the list.""" + list = [] + if type(etype) == types.ClassType: + stype = etype.__name__ + else: + stype = etype + if value is None: + list.append(str(stype) + '\n') + else: + if etype is SyntaxError: + try: + msg, (filename, lineno, offset, line) = value + except: + pass + else: + if not filename: filename = "<string>" + list.append(' File "%s", line %d\n' % + (filename, lineno)) + i = 0 + while i < len(line) and \ + line[i] in string.whitespace: + i = i+1 + list.append(' %s\n' % string.strip(line)) + s = ' ' + for c in line[i:offset-1]: + if c in string.whitespace: + s = s + c + else: + s = s + ' ' + list.append('%s^\n' % s) + value = msg + s = _some_str(value) + if s: + list.append('%s: %s\n' % (str(stype), s)) + else: + list.append('%s\n' % str(stype)) + return list def _some_str(value): - try: - return str(value) - except: - return '<unprintable %s object>' % type(value).__name__ + try: + return str(value) + except: + return '<unprintable %s object>' % type(value).__name__ def print_exc(limit=None, file=None): - """This is a shorthand for 'print_exception(sys.exc_type, - sys.exc_value, sys.exc_traceback, limit, file)'. - (In fact, it uses sys.exc_info() to retrieve the same information - in a thread-safe way.)""" - if not file: - file = sys.stderr - try: - etype, value, tb = sys.exc_info() - print_exception(etype, value, tb, limit, file) - finally: - etype = value = tb = None + """This is a shorthand for 'print_exception(sys.exc_type, + sys.exc_value, sys.exc_traceback, limit, file)'. + (In fact, it uses sys.exc_info() to retrieve the same information + in a thread-safe way.)""" + if not file: + file = sys.stderr + try: + etype, value, tb = sys.exc_info() + print_exception(etype, value, tb, limit, file) + finally: + etype = value = tb = None def print_last(limit=None, file=None): - """This is a shorthand for 'print_exception(sys.last_type, - sys.last_value, sys.last_traceback, limit, file)'.""" - if not file: - file = sys.stderr - print_exception(sys.last_type, sys.last_value, sys.last_traceback, - limit, file) + """This is a shorthand for 'print_exception(sys.last_type, + sys.last_value, sys.last_traceback, limit, file)'.""" + if not file: + file = sys.stderr + print_exception(sys.last_type, sys.last_value, sys.last_traceback, + limit, file) def print_stack(f=None, limit=None, file=None): - """This function prints a stack trace from its invocation point. - The optional 'f' argument can be used to specify an alternate stack - frame at which to start. The optional 'limit' and 'file' arguments - have the same meaning as for print_exception().""" - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - print_list(extract_stack(f, limit), file) + """This function prints a stack trace from its invocation point. + The optional 'f' argument can be used to specify an alternate stack + frame at which to start. The optional 'limit' and 'file' arguments + have the same meaning as for print_exception().""" + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + print_list(extract_stack(f, limit), file) def format_stack(f=None, limit=None): - """A shorthand for 'format_list(extract_stack(f, limit))'.""" - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - return format_list(extract_stack(f, limit)) + """A shorthand for 'format_list(extract_stack(f, limit))'.""" + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + return format_list(extract_stack(f, limit)) def extract_stack(f=None, limit = None): - """Extract the raw traceback from the current stack frame. The - return value has the same format as for extract_tb(). The optional - 'f' and 'limit' arguments have the same meaning as for print_stack(). - Each item in the list is a quadruple (filename, line number, - function name, text), and the entries are in order from oldest - to newest stack frame.""" - if f is None: - try: - raise ZeroDivisionError - except ZeroDivisionError: - f = sys.exc_info()[2].tb_frame.f_back - if limit is None: - if hasattr(sys, 'tracebacklimit'): - limit = sys.tracebacklimit - list = [] - n = 0 - while f is not None and (limit is None or n < limit): - lineno = f.f_lineno # XXX Too bad if -O is used - co = f.f_code - filename = co.co_filename - name = co.co_name - line = linecache.getline(filename, lineno) - if line: line = string.strip(line) - else: line = None - list.append((filename, lineno, name, line)) - f = f.f_back - n = n+1 - list.reverse() - return list + """Extract the raw traceback from the current stack frame. The + return value has the same format as for extract_tb(). The optional + 'f' and 'limit' arguments have the same meaning as for print_stack(). + Each item in the list is a quadruple (filename, line number, + function name, text), and the entries are in order from oldest + to newest stack frame.""" + if f is None: + try: + raise ZeroDivisionError + except ZeroDivisionError: + f = sys.exc_info()[2].tb_frame.f_back + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + list = [] + n = 0 + while f is not None and (limit is None or n < limit): + lineno = f.f_lineno # XXX Too bad if -O is used + co = f.f_code + filename = co.co_filename + name = co.co_name + line = linecache.getline(filename, lineno) + if line: line = string.strip(line) + else: line = None + list.append((filename, lineno, name, line)) + f = f.f_back + n = n+1 + list.reverse() + return list def tb_lineno(tb): - """Calculate the correct line number of the traceback given in tb - (even with -O on).""" + """Calculate the correct line number of the traceback given in tb + (even with -O on).""" - # Coded by Marc-Andre Lemburg from the example of PyCode_Addr2Line() - # in compile.c. - # Revised version by Jim Hugunin to work with JPython too. + # Coded by Marc-Andre Lemburg from the example of PyCode_Addr2Line() + # in compile.c. + # Revised version by Jim Hugunin to work with JPython too. - c = tb.tb_frame.f_code - if not hasattr(c, 'co_lnotab'): - return tb.tb_lineno + c = tb.tb_frame.f_code + if not hasattr(c, 'co_lnotab'): + return tb.tb_lineno - tab = c.co_lnotab - line = c.co_firstlineno - stopat = tb.tb_lasti - addr = 0 - for i in range(0, len(tab), 2): - addr = addr + ord(tab[i]) - if addr > stopat: - break - line = line + ord(tab[i+1]) - return line + tab = c.co_lnotab + line = c.co_firstlineno + stopat = tb.tb_lasti + addr = 0 + for i in range(0, len(tab), 2): + addr = addr + ord(tab[i]) + if addr > stopat: + break + line = line + ord(tab[i+1]) + return line @@ -5,7 +5,7 @@ from TERMIOS import * from termios import * -# Indexes for termios list. +# Indexes for termios list. IFLAG = 0 OFLAG = 1 CFLAG = 2 @@ -15,22 +15,21 @@ OSPEED = 5 CC = 6 def setraw(fd, when=TCSAFLUSH): - """Put terminal into a raw mode.""" - mode = tcgetattr(fd) - mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON) - mode[OFLAG] = mode[OFLAG] & ~(OPOST) - mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB) - mode[CFLAG] = mode[CFLAG] | CS8 - mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG) - mode[CC][VMIN] = 1 - mode[CC][VTIME] = 0 - tcsetattr(fd, when, mode) + """Put terminal into a raw mode.""" + mode = tcgetattr(fd) + mode[IFLAG] = mode[IFLAG] & ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON) + mode[OFLAG] = mode[OFLAG] & ~(OPOST) + mode[CFLAG] = mode[CFLAG] & ~(CSIZE | PARENB) + mode[CFLAG] = mode[CFLAG] | CS8 + mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON | IEXTEN | ISIG) + mode[CC][VMIN] = 1 + mode[CC][VTIME] = 0 + tcsetattr(fd, when, mode) def setcbreak(fd, when=TCSAFLUSH): - """Put terminal into a cbreak mode.""" - mode = tcgetattr(fd) - mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON) - mode[CC][VMIN] = 1 - mode[CC][VTIME] = 0 - tcsetattr(fd, when, mode) - + """Put terminal into a cbreak mode.""" + mode = tcgetattr(fd) + mode[LFLAG] = mode[LFLAG] & ~(ECHO | ICANON) + mode[CC][VMIN] = 1 + mode[CC][VTIME] = 0 + tcsetattr(fd, when, mode) diff --git a/Lib/tzparse.py b/Lib/tzparse.py index 27f1fa1..38e6af1 100644 --- a/Lib/tzparse.py +++ b/Lib/tzparse.py @@ -4,90 +4,90 @@ # XXX Only the typical form "XXXhhYYY;ddd/hh,ddd/hh" is currently supported. tzpat = ('^([A-Z][A-Z][A-Z])([-+]?[0-9]+)([A-Z][A-Z][A-Z]);' - '([0-9]+)/([0-9]+),([0-9]+)/([0-9]+)$') + '([0-9]+)/([0-9]+),([0-9]+)/([0-9]+)$') tzprog = None def tzparse(tzstr): - """Given a timezone spec, return a tuple of information - (tzname, delta, dstname, daystart, hourstart, dayend, hourend), - where 'tzname' is the name of the timezone, 'delta' is the offset - in hours from GMT, 'dstname' is the name of the daylight-saving - timezone, and 'daystart'/'hourstart' and 'dayend'/'hourend' - specify the starting and ending points for daylight saving time.""" - global tzprog - if tzprog is None: - import re - tzprog = re.compile(tzpat) - match = tzprog.match(tzstr) - if not match: - raise ValueError, 'not the TZ syntax I understand' - subs = [] - for i in range(1, 8): - subs.append(match.group(i)) - for i in (1, 3, 4, 5, 6): - subs[i] = eval(subs[i]) - [tzname, delta, dstname, daystart, hourstart, dayend, hourend] = subs - return (tzname, delta, dstname, daystart, hourstart, dayend, hourend) + """Given a timezone spec, return a tuple of information + (tzname, delta, dstname, daystart, hourstart, dayend, hourend), + where 'tzname' is the name of the timezone, 'delta' is the offset + in hours from GMT, 'dstname' is the name of the daylight-saving + timezone, and 'daystart'/'hourstart' and 'dayend'/'hourend' + specify the starting and ending points for daylight saving time.""" + global tzprog + if tzprog is None: + import re + tzprog = re.compile(tzpat) + match = tzprog.match(tzstr) + if not match: + raise ValueError, 'not the TZ syntax I understand' + subs = [] + for i in range(1, 8): + subs.append(match.group(i)) + for i in (1, 3, 4, 5, 6): + subs[i] = eval(subs[i]) + [tzname, delta, dstname, daystart, hourstart, dayend, hourend] = subs + return (tzname, delta, dstname, daystart, hourstart, dayend, hourend) def tzlocaltime(secs, params): - """Given a Unix time in seconds and a tuple of information about - a timezone as returned by tzparse(), return the local time in the - form (year, month, day, hour, min, sec, yday, wday, tzname).""" - import time - (tzname, delta, dstname, daystart, hourstart, dayend, hourend) = params - year, month, days, hours, mins, secs, yday, wday, isdst = \ - time.gmtime(secs - delta*3600) - if (daystart, hourstart) <= (yday+1, hours) < (dayend, hourend): - tzname = dstname - hours = hours + 1 - return year, month, days, hours, mins, secs, yday, wday, tzname + """Given a Unix time in seconds and a tuple of information about + a timezone as returned by tzparse(), return the local time in the + form (year, month, day, hour, min, sec, yday, wday, tzname).""" + import time + (tzname, delta, dstname, daystart, hourstart, dayend, hourend) = params + year, month, days, hours, mins, secs, yday, wday, isdst = \ + time.gmtime(secs - delta*3600) + if (daystart, hourstart) <= (yday+1, hours) < (dayend, hourend): + tzname = dstname + hours = hours + 1 + return year, month, days, hours, mins, secs, yday, wday, tzname def tzset(): - """Determine the current timezone from the "TZ" environment variable.""" - global tzparams, timezone, altzone, daylight, tzname - import os - tzstr = os.environ['TZ'] - tzparams = tzparse(tzstr) - timezone = tzparams[1] * 3600 - altzone = timezone - 3600 - daylight = 1 - tzname = tzparams[0], tzparams[2] + """Determine the current timezone from the "TZ" environment variable.""" + global tzparams, timezone, altzone, daylight, tzname + import os + tzstr = os.environ['TZ'] + tzparams = tzparse(tzstr) + timezone = tzparams[1] * 3600 + altzone = timezone - 3600 + daylight = 1 + tzname = tzparams[0], tzparams[2] def isdst(secs): - """Return true if daylight-saving time is in effect for the given - Unix time in the current timezone.""" - import time - (tzname, delta, dstname, daystart, hourstart, dayend, hourend) = \ - tzparams - year, month, days, hours, mins, secs, yday, wday, isdst = \ - time.gmtime(secs - delta*3600) - return (daystart, hourstart) <= (yday+1, hours) < (dayend, hourend) + """Return true if daylight-saving time is in effect for the given + Unix time in the current timezone.""" + import time + (tzname, delta, dstname, daystart, hourstart, dayend, hourend) = \ + tzparams + year, month, days, hours, mins, secs, yday, wday, isdst = \ + time.gmtime(secs - delta*3600) + return (daystart, hourstart) <= (yday+1, hours) < (dayend, hourend) tzset() def localtime(secs): - """Get the local time in the current timezone.""" - return tzlocaltime(secs, tzparams) + """Get the local time in the current timezone.""" + return tzlocaltime(secs, tzparams) def test(): - from time import asctime, gmtime - import time, sys - now = time.time() - x = localtime(now) - tm = x[:-1] + (0,) - print 'now =', now, '=', asctime(tm), x[-1] - now = now - now % (24*3600) - if sys.argv[1:]: now = now + eval(sys.argv[1]) - x = gmtime(now) - tm = x[:-1] + (0,) - print 'gmtime =', now, '=', asctime(tm), 'yday =', x[-2] - jan1 = now - x[-2]*24*3600 - x = localtime(jan1) - tm = x[:-1] + (0,) - print 'jan1 =', jan1, '=', asctime(tm), x[-1] - for d in range(85, 95) + range(265, 275): - t = jan1 + d*24*3600 - x = localtime(t) - tm = x[:-1] + (0,) - print 'd =', d, 't =', t, '=', asctime(tm), x[-1] + from time import asctime, gmtime + import time, sys + now = time.time() + x = localtime(now) + tm = x[:-1] + (0,) + print 'now =', now, '=', asctime(tm), x[-1] + now = now - now % (24*3600) + if sys.argv[1:]: now = now + eval(sys.argv[1]) + x = gmtime(now) + tm = x[:-1] + (0,) + print 'gmtime =', now, '=', asctime(tm), 'yday =', x[-2] + jan1 = now - x[-2]*24*3600 + x = localtime(jan1) + tm = x[:-1] + (0,) + print 'jan1 =', jan1, '=', asctime(tm), x[-1] + for d in range(85, 95) + range(265, 275): + t = jan1 + d*24*3600 + x = localtime(t) + tm = x[:-1] + (0,) + print 'd =', d, 't =', t, '=', asctime(tm), x[-1] |