# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Safely evaluate Python string literals without using eval().""" import re simple_escapes = {"a": "\a", "b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v", "'": "'", '"': '"', "\\": "\\"} def escape(m): all, tail = m.group(0, 1) assert all.startswith("\\") esc = simple_escapes.get(tail) if esc is not None: return esc if tail.startswith("x"): hexes = tail[1:] if len(hexes) < 2: raise ValueError("invalid hex string escape ('\\%s')" % tail) try: i = int(hexes, 16) except ValueError: raise ValueError("invalid hex string escape ('\\%s')" % tail) else: try: i = int(tail, 8) except ValueError: raise ValueError("invalid octal string escape ('\\%s')" % tail) return chr(i) def evalString(s): assert s.startswith("'") or s.startswith('"'), repr(s[:1]) q = s[0] if s[:3] == q*3: q = q*3 assert s.endswith(q), repr(s[-len(q):]) assert len(s) >= 2*len(q) s = s[len(q):-len(q)] return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s) def test(): for i in range(256): c = chr(i) s = repr(c) e = evalString(s) if e != c: print i, c, s, e if __name__ == "__main__": test()
Name | Type | Size | Permission | Actions |
---|---|---|---|---|
__init__.py | File | 143 B | 0644 |
|
__init__.pyc | File | 174 B | 0644 |
|
__init__.pyo | File | 174 B | 0644 |
|
conv.py | File | 9.4 KB | 0644 |
|
conv.pyc | File | 8 KB | 0644 |
|
conv.pyo | File | 6.87 KB | 0644 |
|
driver.py | File | 5.9 KB | 0644 |
|
driver.pyc | File | 6.31 KB | 0644 |
|
driver.pyo | File | 6.25 KB | 0644 |
|
grammar.py | File | 6.44 KB | 0644 |
|
grammar.pyc | File | 7.5 KB | 0644 |
|
grammar.pyo | File | 7.5 KB | 0644 |
|
literals.py | File | 1.58 KB | 0644 |
|
literals.pyc | File | 1.97 KB | 0644 |
|
literals.pyo | File | 1.74 KB | 0644 |
|
parse.py | File | 7.86 KB | 0644 |
|
parse.pyc | File | 7.07 KB | 0644 |
|
parse.pyo | File | 7.03 KB | 0644 |
|
pgen.py | File | 13.5 KB | 0644 |
|
pgen.pyc | File | 11.95 KB | 0644 |
|
pgen.pyo | File | 11.35 KB | 0644 |
|
token.py | File | 1.23 KB | 0755 |
|
token.pyc | File | 2.25 KB | 0644 |
|
token.pyo | File | 2.25 KB | 0644 |
|
tokenize.py | File | 18.79 KB | 0644 |
|
tokenize.pyc | File | 16.57 KB | 0644 |
|
tokenize.pyo | File | 16.49 KB | 0644 |
|