Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/lib2to3/fixes/fix_zip.py +46 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/__init__.py +4 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/conv.py +257 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/driver.py +177 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/grammar.py +188 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/literals.py +60 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/parse.py +204 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/pgen.py +386 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/token.py +86 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/tokenize.py +564 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/__init__.py +8 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/__main__.py +4 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/README +6 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/bom.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/crlf.py +3 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/different_encoding.py +6 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/false_encoding.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/bad_order.py +5 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_explicit.py +6 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_first.py +6 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_last.py +7 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_parrot.py +13 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_preorder.py +6 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/no_fixer_cls.py +1 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/parrot_example.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/infinite_recursion.py +2669 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/py2_test_grammar.py +971 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/py3_test_grammar.py +956 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/pytree_idempotency.py +94 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/support.py +58 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_all_fixers.py +42 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_fixers.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_main.py +139 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_parser.py +717 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_pytree.py +472 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_refactor.py +337 -0
- miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_util.py +591 -0
- miniconda3/envs/ladir/lib/python3.10/logging/__init__.py +2261 -0
- miniconda3/envs/ladir/lib/python3.10/logging/config.py +947 -0
- miniconda3/envs/ladir/lib/python3.10/logging/handlers.py +1587 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/__init__.py +37 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/connection.py +973 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/context.py +376 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/dummy/__init__.py +126 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/dummy/connection.py +75 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/forkserver.py +348 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/heap.py +337 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/managers.py +1378 -0
- miniconda3/envs/ladir/lib/python3.10/multiprocessing/pool.py +957 -0
miniconda3/envs/ladir/lib/python3.10/lib2to3/fixes/fix_zip.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fixer that changes zip(seq0, seq1, ...) into list(zip(seq0, seq1, ...)
|
| 3 |
+
unless there exists a 'from future_builtins import zip' statement in the
|
| 4 |
+
top-level namespace.
|
| 5 |
+
|
| 6 |
+
We avoid the transformation if the zip() call is directly contained in
|
| 7 |
+
iter(<>), list(<>), tuple(<>), sorted(<>), ...join(<>), or for V in <>:.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
# Local imports
|
| 11 |
+
from .. import fixer_base
|
| 12 |
+
from ..pytree import Node
|
| 13 |
+
from ..pygram import python_symbols as syms
|
| 14 |
+
from ..fixer_util import Name, ArgList, in_special_context
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class FixZip(fixer_base.ConditionalFix):
|
| 18 |
+
|
| 19 |
+
BM_compatible = True
|
| 20 |
+
PATTERN = """
|
| 21 |
+
power< 'zip' args=trailer< '(' [any] ')' > [trailers=trailer*]
|
| 22 |
+
>
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
skip_on = "future_builtins.zip"
|
| 26 |
+
|
| 27 |
+
def transform(self, node, results):
|
| 28 |
+
if self.should_skip(node):
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
if in_special_context(node):
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
args = results['args'].clone()
|
| 35 |
+
args.prefix = ""
|
| 36 |
+
|
| 37 |
+
trailers = []
|
| 38 |
+
if 'trailers' in results:
|
| 39 |
+
trailers = [n.clone() for n in results['trailers']]
|
| 40 |
+
for n in trailers:
|
| 41 |
+
n.prefix = ""
|
| 42 |
+
|
| 43 |
+
new = Node(syms.power, [Name("zip"), args], prefix="")
|
| 44 |
+
new = Node(syms.power, [Name("list"), ArgList([new])] + trailers)
|
| 45 |
+
new.prefix = node.prefix
|
| 46 |
+
return new
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
"""The pgen2 package."""
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/conv.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
"""Convert graminit.[ch] spit out by pgen to Python code.
|
| 5 |
+
|
| 6 |
+
Pgen is the Python parser generator. It is useful to quickly create a
|
| 7 |
+
parser from a grammar file in Python's grammar notation. But I don't
|
| 8 |
+
want my parsers to be written in C (yet), so I'm translating the
|
| 9 |
+
parsing tables to Python data structures and writing a Python parse
|
| 10 |
+
engine.
|
| 11 |
+
|
| 12 |
+
Note that the token numbers are constants determined by the standard
|
| 13 |
+
Python tokenizer. The standard token module defines these numbers and
|
| 14 |
+
their names (the names are not used much). The token numbers are
|
| 15 |
+
hardcoded into the Python tokenizer and into pgen. A Python
|
| 16 |
+
implementation of the Python tokenizer is also available, in the
|
| 17 |
+
standard tokenize module.
|
| 18 |
+
|
| 19 |
+
On the other hand, symbol numbers (representing the grammar's
|
| 20 |
+
non-terminals) are assigned by pgen based on the actual grammar
|
| 21 |
+
input.
|
| 22 |
+
|
| 23 |
+
Note: this module is pretty much obsolete; the pgen module generates
|
| 24 |
+
equivalent grammar tables directly from the Grammar.txt input file
|
| 25 |
+
without having to invoke the Python pgen C program.
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
# Python imports
|
| 30 |
+
import re
|
| 31 |
+
|
| 32 |
+
# Local imports
|
| 33 |
+
from pgen2 import grammar, token
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Converter(grammar.Grammar):
|
| 37 |
+
"""Grammar subclass that reads classic pgen output files.
|
| 38 |
+
|
| 39 |
+
The run() method reads the tables as produced by the pgen parser
|
| 40 |
+
generator, typically contained in two C files, graminit.h and
|
| 41 |
+
graminit.c. The other methods are for internal use only.
|
| 42 |
+
|
| 43 |
+
See the base class for more documentation.
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def run(self, graminit_h, graminit_c):
|
| 48 |
+
"""Load the grammar tables from the text files written by pgen."""
|
| 49 |
+
self.parse_graminit_h(graminit_h)
|
| 50 |
+
self.parse_graminit_c(graminit_c)
|
| 51 |
+
self.finish_off()
|
| 52 |
+
|
| 53 |
+
def parse_graminit_h(self, filename):
|
| 54 |
+
"""Parse the .h file written by pgen. (Internal)
|
| 55 |
+
|
| 56 |
+
This file is a sequence of #define statements defining the
|
| 57 |
+
nonterminals of the grammar as numbers. We build two tables
|
| 58 |
+
mapping the numbers to names and back.
|
| 59 |
+
|
| 60 |
+
"""
|
| 61 |
+
try:
|
| 62 |
+
f = open(filename)
|
| 63 |
+
except OSError as err:
|
| 64 |
+
print("Can't open %s: %s" % (filename, err))
|
| 65 |
+
return False
|
| 66 |
+
self.symbol2number = {}
|
| 67 |
+
self.number2symbol = {}
|
| 68 |
+
lineno = 0
|
| 69 |
+
for line in f:
|
| 70 |
+
lineno += 1
|
| 71 |
+
mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line)
|
| 72 |
+
if not mo and line.strip():
|
| 73 |
+
print("%s(%s): can't parse %s" % (filename, lineno,
|
| 74 |
+
line.strip()))
|
| 75 |
+
else:
|
| 76 |
+
symbol, number = mo.groups()
|
| 77 |
+
number = int(number)
|
| 78 |
+
assert symbol not in self.symbol2number
|
| 79 |
+
assert number not in self.number2symbol
|
| 80 |
+
self.symbol2number[symbol] = number
|
| 81 |
+
self.number2symbol[number] = symbol
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def parse_graminit_c(self, filename):
|
| 85 |
+
"""Parse the .c file written by pgen. (Internal)
|
| 86 |
+
|
| 87 |
+
The file looks as follows. The first two lines are always this:
|
| 88 |
+
|
| 89 |
+
#include "pgenheaders.h"
|
| 90 |
+
#include "grammar.h"
|
| 91 |
+
|
| 92 |
+
After that come four blocks:
|
| 93 |
+
|
| 94 |
+
1) one or more state definitions
|
| 95 |
+
2) a table defining dfas
|
| 96 |
+
3) a table defining labels
|
| 97 |
+
4) a struct defining the grammar
|
| 98 |
+
|
| 99 |
+
A state definition has the following form:
|
| 100 |
+
- one or more arc arrays, each of the form:
|
| 101 |
+
static arc arcs_<n>_<m>[<k>] = {
|
| 102 |
+
{<i>, <j>},
|
| 103 |
+
...
|
| 104 |
+
};
|
| 105 |
+
- followed by a state array, of the form:
|
| 106 |
+
static state states_<s>[<t>] = {
|
| 107 |
+
{<k>, arcs_<n>_<m>},
|
| 108 |
+
...
|
| 109 |
+
};
|
| 110 |
+
|
| 111 |
+
"""
|
| 112 |
+
try:
|
| 113 |
+
f = open(filename)
|
| 114 |
+
except OSError as err:
|
| 115 |
+
print("Can't open %s: %s" % (filename, err))
|
| 116 |
+
return False
|
| 117 |
+
# The code below essentially uses f's iterator-ness!
|
| 118 |
+
lineno = 0
|
| 119 |
+
|
| 120 |
+
# Expect the two #include lines
|
| 121 |
+
lineno, line = lineno+1, next(f)
|
| 122 |
+
assert line == '#include "pgenheaders.h"\n', (lineno, line)
|
| 123 |
+
lineno, line = lineno+1, next(f)
|
| 124 |
+
assert line == '#include "grammar.h"\n', (lineno, line)
|
| 125 |
+
|
| 126 |
+
# Parse the state definitions
|
| 127 |
+
lineno, line = lineno+1, next(f)
|
| 128 |
+
allarcs = {}
|
| 129 |
+
states = []
|
| 130 |
+
while line.startswith("static arc "):
|
| 131 |
+
while line.startswith("static arc "):
|
| 132 |
+
mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$",
|
| 133 |
+
line)
|
| 134 |
+
assert mo, (lineno, line)
|
| 135 |
+
n, m, k = list(map(int, mo.groups()))
|
| 136 |
+
arcs = []
|
| 137 |
+
for _ in range(k):
|
| 138 |
+
lineno, line = lineno+1, next(f)
|
| 139 |
+
mo = re.match(r"\s+{(\d+), (\d+)},$", line)
|
| 140 |
+
assert mo, (lineno, line)
|
| 141 |
+
i, j = list(map(int, mo.groups()))
|
| 142 |
+
arcs.append((i, j))
|
| 143 |
+
lineno, line = lineno+1, next(f)
|
| 144 |
+
assert line == "};\n", (lineno, line)
|
| 145 |
+
allarcs[(n, m)] = arcs
|
| 146 |
+
lineno, line = lineno+1, next(f)
|
| 147 |
+
mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line)
|
| 148 |
+
assert mo, (lineno, line)
|
| 149 |
+
s, t = list(map(int, mo.groups()))
|
| 150 |
+
assert s == len(states), (lineno, line)
|
| 151 |
+
state = []
|
| 152 |
+
for _ in range(t):
|
| 153 |
+
lineno, line = lineno+1, next(f)
|
| 154 |
+
mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line)
|
| 155 |
+
assert mo, (lineno, line)
|
| 156 |
+
k, n, m = list(map(int, mo.groups()))
|
| 157 |
+
arcs = allarcs[n, m]
|
| 158 |
+
assert k == len(arcs), (lineno, line)
|
| 159 |
+
state.append(arcs)
|
| 160 |
+
states.append(state)
|
| 161 |
+
lineno, line = lineno+1, next(f)
|
| 162 |
+
assert line == "};\n", (lineno, line)
|
| 163 |
+
lineno, line = lineno+1, next(f)
|
| 164 |
+
self.states = states
|
| 165 |
+
|
| 166 |
+
# Parse the dfas
|
| 167 |
+
dfas = {}
|
| 168 |
+
mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line)
|
| 169 |
+
assert mo, (lineno, line)
|
| 170 |
+
ndfas = int(mo.group(1))
|
| 171 |
+
for i in range(ndfas):
|
| 172 |
+
lineno, line = lineno+1, next(f)
|
| 173 |
+
mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$',
|
| 174 |
+
line)
|
| 175 |
+
assert mo, (lineno, line)
|
| 176 |
+
symbol = mo.group(2)
|
| 177 |
+
number, x, y, z = list(map(int, mo.group(1, 3, 4, 5)))
|
| 178 |
+
assert self.symbol2number[symbol] == number, (lineno, line)
|
| 179 |
+
assert self.number2symbol[number] == symbol, (lineno, line)
|
| 180 |
+
assert x == 0, (lineno, line)
|
| 181 |
+
state = states[z]
|
| 182 |
+
assert y == len(state), (lineno, line)
|
| 183 |
+
lineno, line = lineno+1, next(f)
|
| 184 |
+
mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line)
|
| 185 |
+
assert mo, (lineno, line)
|
| 186 |
+
first = {}
|
| 187 |
+
rawbitset = eval(mo.group(1))
|
| 188 |
+
for i, c in enumerate(rawbitset):
|
| 189 |
+
byte = ord(c)
|
| 190 |
+
for j in range(8):
|
| 191 |
+
if byte & (1<<j):
|
| 192 |
+
first[i*8 + j] = 1
|
| 193 |
+
dfas[number] = (state, first)
|
| 194 |
+
lineno, line = lineno+1, next(f)
|
| 195 |
+
assert line == "};\n", (lineno, line)
|
| 196 |
+
self.dfas = dfas
|
| 197 |
+
|
| 198 |
+
# Parse the labels
|
| 199 |
+
labels = []
|
| 200 |
+
lineno, line = lineno+1, next(f)
|
| 201 |
+
mo = re.match(r"static label labels\[(\d+)\] = {$", line)
|
| 202 |
+
assert mo, (lineno, line)
|
| 203 |
+
nlabels = int(mo.group(1))
|
| 204 |
+
for i in range(nlabels):
|
| 205 |
+
lineno, line = lineno+1, next(f)
|
| 206 |
+
mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line)
|
| 207 |
+
assert mo, (lineno, line)
|
| 208 |
+
x, y = mo.groups()
|
| 209 |
+
x = int(x)
|
| 210 |
+
if y == "0":
|
| 211 |
+
y = None
|
| 212 |
+
else:
|
| 213 |
+
y = eval(y)
|
| 214 |
+
labels.append((x, y))
|
| 215 |
+
lineno, line = lineno+1, next(f)
|
| 216 |
+
assert line == "};\n", (lineno, line)
|
| 217 |
+
self.labels = labels
|
| 218 |
+
|
| 219 |
+
# Parse the grammar struct
|
| 220 |
+
lineno, line = lineno+1, next(f)
|
| 221 |
+
assert line == "grammar _PyParser_Grammar = {\n", (lineno, line)
|
| 222 |
+
lineno, line = lineno+1, next(f)
|
| 223 |
+
mo = re.match(r"\s+(\d+),$", line)
|
| 224 |
+
assert mo, (lineno, line)
|
| 225 |
+
ndfas = int(mo.group(1))
|
| 226 |
+
assert ndfas == len(self.dfas)
|
| 227 |
+
lineno, line = lineno+1, next(f)
|
| 228 |
+
assert line == "\tdfas,\n", (lineno, line)
|
| 229 |
+
lineno, line = lineno+1, next(f)
|
| 230 |
+
mo = re.match(r"\s+{(\d+), labels},$", line)
|
| 231 |
+
assert mo, (lineno, line)
|
| 232 |
+
nlabels = int(mo.group(1))
|
| 233 |
+
assert nlabels == len(self.labels), (lineno, line)
|
| 234 |
+
lineno, line = lineno+1, next(f)
|
| 235 |
+
mo = re.match(r"\s+(\d+)$", line)
|
| 236 |
+
assert mo, (lineno, line)
|
| 237 |
+
start = int(mo.group(1))
|
| 238 |
+
assert start in self.number2symbol, (lineno, line)
|
| 239 |
+
self.start = start
|
| 240 |
+
lineno, line = lineno+1, next(f)
|
| 241 |
+
assert line == "};\n", (lineno, line)
|
| 242 |
+
try:
|
| 243 |
+
lineno, line = lineno+1, next(f)
|
| 244 |
+
except StopIteration:
|
| 245 |
+
pass
|
| 246 |
+
else:
|
| 247 |
+
assert 0, (lineno, line)
|
| 248 |
+
|
| 249 |
+
def finish_off(self):
|
| 250 |
+
"""Create additional useful structures. (Internal)."""
|
| 251 |
+
self.keywords = {} # map from keyword strings to arc labels
|
| 252 |
+
self.tokens = {} # map from numeric token values to arc labels
|
| 253 |
+
for ilabel, (type, value) in enumerate(self.labels):
|
| 254 |
+
if type == token.NAME and value is not None:
|
| 255 |
+
self.keywords[value] = ilabel
|
| 256 |
+
elif value is None:
|
| 257 |
+
self.tokens[type] = ilabel
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
# Modifications:
|
| 5 |
+
# Copyright 2006 Google, Inc. All Rights Reserved.
|
| 6 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 7 |
+
|
| 8 |
+
"""Parser driver.
|
| 9 |
+
|
| 10 |
+
This provides a high-level interface to parse a file into a syntax tree.
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
__author__ = "Guido van Rossum <guido@python.org>"
|
| 15 |
+
|
| 16 |
+
__all__ = ["Driver", "load_grammar"]
|
| 17 |
+
|
| 18 |
+
# Python imports
|
| 19 |
+
import io
|
| 20 |
+
import os
|
| 21 |
+
import logging
|
| 22 |
+
import pkgutil
|
| 23 |
+
import sys
|
| 24 |
+
|
| 25 |
+
# Pgen imports
|
| 26 |
+
from . import grammar, parse, token, tokenize, pgen
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Driver(object):
|
| 30 |
+
|
| 31 |
+
def __init__(self, grammar, convert=None, logger=None):
|
| 32 |
+
self.grammar = grammar
|
| 33 |
+
if logger is None:
|
| 34 |
+
logger = logging.getLogger()
|
| 35 |
+
self.logger = logger
|
| 36 |
+
self.convert = convert
|
| 37 |
+
|
| 38 |
+
def parse_tokens(self, tokens, debug=False):
|
| 39 |
+
"""Parse a series of tokens and return the syntax tree."""
|
| 40 |
+
# XXX Move the prefix computation into a wrapper around tokenize.
|
| 41 |
+
p = parse.Parser(self.grammar, self.convert)
|
| 42 |
+
p.setup()
|
| 43 |
+
lineno = 1
|
| 44 |
+
column = 0
|
| 45 |
+
type = value = start = end = line_text = None
|
| 46 |
+
prefix = ""
|
| 47 |
+
for quintuple in tokens:
|
| 48 |
+
type, value, start, end, line_text = quintuple
|
| 49 |
+
if start != (lineno, column):
|
| 50 |
+
assert (lineno, column) <= start, ((lineno, column), start)
|
| 51 |
+
s_lineno, s_column = start
|
| 52 |
+
if lineno < s_lineno:
|
| 53 |
+
prefix += "\n" * (s_lineno - lineno)
|
| 54 |
+
lineno = s_lineno
|
| 55 |
+
column = 0
|
| 56 |
+
if column < s_column:
|
| 57 |
+
prefix += line_text[column:s_column]
|
| 58 |
+
column = s_column
|
| 59 |
+
if type in (tokenize.COMMENT, tokenize.NL):
|
| 60 |
+
prefix += value
|
| 61 |
+
lineno, column = end
|
| 62 |
+
if value.endswith("\n"):
|
| 63 |
+
lineno += 1
|
| 64 |
+
column = 0
|
| 65 |
+
continue
|
| 66 |
+
if type == token.OP:
|
| 67 |
+
type = grammar.opmap[value]
|
| 68 |
+
if debug:
|
| 69 |
+
self.logger.debug("%s %r (prefix=%r)",
|
| 70 |
+
token.tok_name[type], value, prefix)
|
| 71 |
+
if p.addtoken(type, value, (prefix, start)):
|
| 72 |
+
if debug:
|
| 73 |
+
self.logger.debug("Stop.")
|
| 74 |
+
break
|
| 75 |
+
prefix = ""
|
| 76 |
+
lineno, column = end
|
| 77 |
+
if value.endswith("\n"):
|
| 78 |
+
lineno += 1
|
| 79 |
+
column = 0
|
| 80 |
+
else:
|
| 81 |
+
# We never broke out -- EOF is too soon (how can this happen???)
|
| 82 |
+
raise parse.ParseError("incomplete input",
|
| 83 |
+
type, value, (prefix, start))
|
| 84 |
+
return p.rootnode
|
| 85 |
+
|
| 86 |
+
def parse_stream_raw(self, stream, debug=False):
|
| 87 |
+
"""Parse a stream and return the syntax tree."""
|
| 88 |
+
tokens = tokenize.generate_tokens(stream.readline)
|
| 89 |
+
return self.parse_tokens(tokens, debug)
|
| 90 |
+
|
| 91 |
+
def parse_stream(self, stream, debug=False):
|
| 92 |
+
"""Parse a stream and return the syntax tree."""
|
| 93 |
+
return self.parse_stream_raw(stream, debug)
|
| 94 |
+
|
| 95 |
+
def parse_file(self, filename, encoding=None, debug=False):
|
| 96 |
+
"""Parse a file and return the syntax tree."""
|
| 97 |
+
with io.open(filename, "r", encoding=encoding) as stream:
|
| 98 |
+
return self.parse_stream(stream, debug)
|
| 99 |
+
|
| 100 |
+
def parse_string(self, text, debug=False):
|
| 101 |
+
"""Parse a string and return the syntax tree."""
|
| 102 |
+
tokens = tokenize.generate_tokens(io.StringIO(text).readline)
|
| 103 |
+
return self.parse_tokens(tokens, debug)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _generate_pickle_name(gt):
|
| 107 |
+
head, tail = os.path.splitext(gt)
|
| 108 |
+
if tail == ".txt":
|
| 109 |
+
tail = ""
|
| 110 |
+
return head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def load_grammar(gt="Grammar.txt", gp=None,
|
| 114 |
+
save=True, force=False, logger=None):
|
| 115 |
+
"""Load the grammar (maybe from a pickle)."""
|
| 116 |
+
if logger is None:
|
| 117 |
+
logger = logging.getLogger()
|
| 118 |
+
gp = _generate_pickle_name(gt) if gp is None else gp
|
| 119 |
+
if force or not _newer(gp, gt):
|
| 120 |
+
logger.info("Generating grammar tables from %s", gt)
|
| 121 |
+
g = pgen.generate_grammar(gt)
|
| 122 |
+
if save:
|
| 123 |
+
logger.info("Writing grammar tables to %s", gp)
|
| 124 |
+
try:
|
| 125 |
+
g.dump(gp)
|
| 126 |
+
except OSError as e:
|
| 127 |
+
logger.info("Writing failed: %s", e)
|
| 128 |
+
else:
|
| 129 |
+
g = grammar.Grammar()
|
| 130 |
+
g.load(gp)
|
| 131 |
+
return g
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _newer(a, b):
|
| 135 |
+
"""Inquire whether file a was written since file b."""
|
| 136 |
+
if not os.path.exists(a):
|
| 137 |
+
return False
|
| 138 |
+
if not os.path.exists(b):
|
| 139 |
+
return True
|
| 140 |
+
return os.path.getmtime(a) >= os.path.getmtime(b)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def load_packaged_grammar(package, grammar_source):
|
| 144 |
+
"""Normally, loads a pickled grammar by doing
|
| 145 |
+
pkgutil.get_data(package, pickled_grammar)
|
| 146 |
+
where *pickled_grammar* is computed from *grammar_source* by adding the
|
| 147 |
+
Python version and using a ``.pickle`` extension.
|
| 148 |
+
|
| 149 |
+
However, if *grammar_source* is an extant file, load_grammar(grammar_source)
|
| 150 |
+
is called instead. This facilitates using a packaged grammar file when needed
|
| 151 |
+
but preserves load_grammar's automatic regeneration behavior when possible.
|
| 152 |
+
|
| 153 |
+
"""
|
| 154 |
+
if os.path.isfile(grammar_source):
|
| 155 |
+
return load_grammar(grammar_source)
|
| 156 |
+
pickled_name = _generate_pickle_name(os.path.basename(grammar_source))
|
| 157 |
+
data = pkgutil.get_data(package, pickled_name)
|
| 158 |
+
g = grammar.Grammar()
|
| 159 |
+
g.loads(data)
|
| 160 |
+
return g
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main(*args):
|
| 164 |
+
"""Main program, when run as a script: produce grammar pickle files.
|
| 165 |
+
|
| 166 |
+
Calls load_grammar for each argument, a path to a grammar text file.
|
| 167 |
+
"""
|
| 168 |
+
if not args:
|
| 169 |
+
args = sys.argv[1:]
|
| 170 |
+
logging.basicConfig(level=logging.INFO, stream=sys.stdout,
|
| 171 |
+
format='%(message)s')
|
| 172 |
+
for gt in args:
|
| 173 |
+
load_grammar(gt, save=True, force=True)
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
sys.exit(int(not main()))
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/grammar.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
"""This module defines the data structures used to represent a grammar.
|
| 5 |
+
|
| 6 |
+
These are a bit arcane because they are derived from the data
|
| 7 |
+
structures used by Python's 'pgen' parser generator.
|
| 8 |
+
|
| 9 |
+
There's also a table here mapping operators to their names in the
|
| 10 |
+
token module; the Python tokenize module reports all operators as the
|
| 11 |
+
fallback token code OP, but the parser needs the actual token code.
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
# Python imports
|
| 16 |
+
import pickle
|
| 17 |
+
|
| 18 |
+
# Local imports
|
| 19 |
+
from . import token
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Grammar(object):
|
| 23 |
+
"""Pgen parsing tables conversion class.
|
| 24 |
+
|
| 25 |
+
Once initialized, this class supplies the grammar tables for the
|
| 26 |
+
parsing engine implemented by parse.py. The parsing engine
|
| 27 |
+
accesses the instance variables directly. The class here does not
|
| 28 |
+
provide initialization of the tables; several subclasses exist to
|
| 29 |
+
do this (see the conv and pgen modules).
|
| 30 |
+
|
| 31 |
+
The load() method reads the tables from a pickle file, which is
|
| 32 |
+
much faster than the other ways offered by subclasses. The pickle
|
| 33 |
+
file is written by calling dump() (after loading the grammar
|
| 34 |
+
tables using a subclass). The report() method prints a readable
|
| 35 |
+
representation of the tables to stdout, for debugging.
|
| 36 |
+
|
| 37 |
+
The instance variables are as follows:
|
| 38 |
+
|
| 39 |
+
symbol2number -- a dict mapping symbol names to numbers. Symbol
|
| 40 |
+
numbers are always 256 or higher, to distinguish
|
| 41 |
+
them from token numbers, which are between 0 and
|
| 42 |
+
255 (inclusive).
|
| 43 |
+
|
| 44 |
+
number2symbol -- a dict mapping numbers to symbol names;
|
| 45 |
+
these two are each other's inverse.
|
| 46 |
+
|
| 47 |
+
states -- a list of DFAs, where each DFA is a list of
|
| 48 |
+
states, each state is a list of arcs, and each
|
| 49 |
+
arc is a (i, j) pair where i is a label and j is
|
| 50 |
+
a state number. The DFA number is the index into
|
| 51 |
+
this list. (This name is slightly confusing.)
|
| 52 |
+
Final states are represented by a special arc of
|
| 53 |
+
the form (0, j) where j is its own state number.
|
| 54 |
+
|
| 55 |
+
dfas -- a dict mapping symbol numbers to (DFA, first)
|
| 56 |
+
pairs, where DFA is an item from the states list
|
| 57 |
+
above, and first is a set of tokens that can
|
| 58 |
+
begin this grammar rule (represented by a dict
|
| 59 |
+
whose values are always 1).
|
| 60 |
+
|
| 61 |
+
labels -- a list of (x, y) pairs where x is either a token
|
| 62 |
+
number or a symbol number, and y is either None
|
| 63 |
+
or a string; the strings are keywords. The label
|
| 64 |
+
number is the index in this list; label numbers
|
| 65 |
+
are used to mark state transitions (arcs) in the
|
| 66 |
+
DFAs.
|
| 67 |
+
|
| 68 |
+
start -- the number of the grammar's start symbol.
|
| 69 |
+
|
| 70 |
+
keywords -- a dict mapping keyword strings to arc labels.
|
| 71 |
+
|
| 72 |
+
tokens -- a dict mapping token numbers to arc labels.
|
| 73 |
+
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(self):
|
| 77 |
+
self.symbol2number = {}
|
| 78 |
+
self.number2symbol = {}
|
| 79 |
+
self.states = []
|
| 80 |
+
self.dfas = {}
|
| 81 |
+
self.labels = [(0, "EMPTY")]
|
| 82 |
+
self.keywords = {}
|
| 83 |
+
self.tokens = {}
|
| 84 |
+
self.symbol2label = {}
|
| 85 |
+
self.start = 256
|
| 86 |
+
|
| 87 |
+
def dump(self, filename):
|
| 88 |
+
"""Dump the grammar tables to a pickle file."""
|
| 89 |
+
with open(filename, "wb") as f:
|
| 90 |
+
pickle.dump(self.__dict__, f, pickle.HIGHEST_PROTOCOL)
|
| 91 |
+
|
| 92 |
+
def load(self, filename):
|
| 93 |
+
"""Load the grammar tables from a pickle file."""
|
| 94 |
+
with open(filename, "rb") as f:
|
| 95 |
+
d = pickle.load(f)
|
| 96 |
+
self.__dict__.update(d)
|
| 97 |
+
|
| 98 |
+
def loads(self, pkl):
|
| 99 |
+
"""Load the grammar tables from a pickle bytes object."""
|
| 100 |
+
self.__dict__.update(pickle.loads(pkl))
|
| 101 |
+
|
| 102 |
+
def copy(self):
|
| 103 |
+
"""
|
| 104 |
+
Copy the grammar.
|
| 105 |
+
"""
|
| 106 |
+
new = self.__class__()
|
| 107 |
+
for dict_attr in ("symbol2number", "number2symbol", "dfas", "keywords",
|
| 108 |
+
"tokens", "symbol2label"):
|
| 109 |
+
setattr(new, dict_attr, getattr(self, dict_attr).copy())
|
| 110 |
+
new.labels = self.labels[:]
|
| 111 |
+
new.states = self.states[:]
|
| 112 |
+
new.start = self.start
|
| 113 |
+
return new
|
| 114 |
+
|
| 115 |
+
def report(self):
|
| 116 |
+
"""Dump the grammar tables to standard output, for debugging."""
|
| 117 |
+
from pprint import pprint
|
| 118 |
+
print("s2n")
|
| 119 |
+
pprint(self.symbol2number)
|
| 120 |
+
print("n2s")
|
| 121 |
+
pprint(self.number2symbol)
|
| 122 |
+
print("states")
|
| 123 |
+
pprint(self.states)
|
| 124 |
+
print("dfas")
|
| 125 |
+
pprint(self.dfas)
|
| 126 |
+
print("labels")
|
| 127 |
+
pprint(self.labels)
|
| 128 |
+
print("start", self.start)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# Map from operator to number (since tokenize doesn't do this)
|
| 132 |
+
|
| 133 |
+
opmap_raw = """
|
| 134 |
+
( LPAR
|
| 135 |
+
) RPAR
|
| 136 |
+
[ LSQB
|
| 137 |
+
] RSQB
|
| 138 |
+
: COLON
|
| 139 |
+
, COMMA
|
| 140 |
+
; SEMI
|
| 141 |
+
+ PLUS
|
| 142 |
+
- MINUS
|
| 143 |
+
* STAR
|
| 144 |
+
/ SLASH
|
| 145 |
+
| VBAR
|
| 146 |
+
& AMPER
|
| 147 |
+
< LESS
|
| 148 |
+
> GREATER
|
| 149 |
+
= EQUAL
|
| 150 |
+
. DOT
|
| 151 |
+
% PERCENT
|
| 152 |
+
` BACKQUOTE
|
| 153 |
+
{ LBRACE
|
| 154 |
+
} RBRACE
|
| 155 |
+
@ AT
|
| 156 |
+
@= ATEQUAL
|
| 157 |
+
== EQEQUAL
|
| 158 |
+
!= NOTEQUAL
|
| 159 |
+
<> NOTEQUAL
|
| 160 |
+
<= LESSEQUAL
|
| 161 |
+
>= GREATEREQUAL
|
| 162 |
+
~ TILDE
|
| 163 |
+
^ CIRCUMFLEX
|
| 164 |
+
<< LEFTSHIFT
|
| 165 |
+
>> RIGHTSHIFT
|
| 166 |
+
** DOUBLESTAR
|
| 167 |
+
+= PLUSEQUAL
|
| 168 |
+
-= MINEQUAL
|
| 169 |
+
*= STAREQUAL
|
| 170 |
+
/= SLASHEQUAL
|
| 171 |
+
%= PERCENTEQUAL
|
| 172 |
+
&= AMPEREQUAL
|
| 173 |
+
|= VBAREQUAL
|
| 174 |
+
^= CIRCUMFLEXEQUAL
|
| 175 |
+
<<= LEFTSHIFTEQUAL
|
| 176 |
+
>>= RIGHTSHIFTEQUAL
|
| 177 |
+
**= DOUBLESTAREQUAL
|
| 178 |
+
// DOUBLESLASH
|
| 179 |
+
//= DOUBLESLASHEQUAL
|
| 180 |
+
-> RARROW
|
| 181 |
+
:= COLONEQUAL
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
opmap = {}
|
| 185 |
+
for line in opmap_raw.splitlines():
|
| 186 |
+
if line:
|
| 187 |
+
op, name = line.split()
|
| 188 |
+
opmap[op] = getattr(token, name)
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/literals.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
"""Safely evaluate Python string literals without using eval()."""
|
| 5 |
+
|
| 6 |
+
import re
|
| 7 |
+
|
| 8 |
+
simple_escapes = {"a": "\a",
|
| 9 |
+
"b": "\b",
|
| 10 |
+
"f": "\f",
|
| 11 |
+
"n": "\n",
|
| 12 |
+
"r": "\r",
|
| 13 |
+
"t": "\t",
|
| 14 |
+
"v": "\v",
|
| 15 |
+
"'": "'",
|
| 16 |
+
'"': '"',
|
| 17 |
+
"\\": "\\"}
|
| 18 |
+
|
| 19 |
+
def escape(m):
|
| 20 |
+
all, tail = m.group(0, 1)
|
| 21 |
+
assert all.startswith("\\")
|
| 22 |
+
esc = simple_escapes.get(tail)
|
| 23 |
+
if esc is not None:
|
| 24 |
+
return esc
|
| 25 |
+
if tail.startswith("x"):
|
| 26 |
+
hexes = tail[1:]
|
| 27 |
+
if len(hexes) < 2:
|
| 28 |
+
raise ValueError("invalid hex string escape ('\\%s')" % tail)
|
| 29 |
+
try:
|
| 30 |
+
i = int(hexes, 16)
|
| 31 |
+
except ValueError:
|
| 32 |
+
raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
|
| 33 |
+
else:
|
| 34 |
+
try:
|
| 35 |
+
i = int(tail, 8)
|
| 36 |
+
except ValueError:
|
| 37 |
+
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
|
| 38 |
+
return chr(i)
|
| 39 |
+
|
| 40 |
+
def evalString(s):
|
| 41 |
+
assert s.startswith("'") or s.startswith('"'), repr(s[:1])
|
| 42 |
+
q = s[0]
|
| 43 |
+
if s[:3] == q*3:
|
| 44 |
+
q = q*3
|
| 45 |
+
assert s.endswith(q), repr(s[-len(q):])
|
| 46 |
+
assert len(s) >= 2*len(q)
|
| 47 |
+
s = s[len(q):-len(q)]
|
| 48 |
+
return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s)
|
| 49 |
+
|
| 50 |
+
def test():
|
| 51 |
+
for i in range(256):
|
| 52 |
+
c = chr(i)
|
| 53 |
+
s = repr(c)
|
| 54 |
+
e = evalString(s)
|
| 55 |
+
if e != c:
|
| 56 |
+
print(i, c, s, e)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
test()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/parse.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
"""Parser engine for the grammar tables generated by pgen.
|
| 5 |
+
|
| 6 |
+
The grammar table must be loaded first.
|
| 7 |
+
|
| 8 |
+
See Parser/parser.c in the Python distribution for additional info on
|
| 9 |
+
how this parsing engine works.
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# Local imports
|
| 14 |
+
from . import token
|
| 15 |
+
|
| 16 |
+
class ParseError(Exception):
|
| 17 |
+
"""Exception to signal the parser is stuck."""
|
| 18 |
+
|
| 19 |
+
def __init__(self, msg, type, value, context):
|
| 20 |
+
Exception.__init__(self, "%s: type=%r, value=%r, context=%r" %
|
| 21 |
+
(msg, type, value, context))
|
| 22 |
+
self.msg = msg
|
| 23 |
+
self.type = type
|
| 24 |
+
self.value = value
|
| 25 |
+
self.context = context
|
| 26 |
+
|
| 27 |
+
def __reduce__(self):
|
| 28 |
+
return type(self), (self.msg, self.type, self.value, self.context)
|
| 29 |
+
|
| 30 |
+
class Parser(object):
|
| 31 |
+
"""Parser engine.
|
| 32 |
+
|
| 33 |
+
The proper usage sequence is:
|
| 34 |
+
|
| 35 |
+
p = Parser(grammar, [converter]) # create instance
|
| 36 |
+
p.setup([start]) # prepare for parsing
|
| 37 |
+
<for each input token>:
|
| 38 |
+
if p.addtoken(...): # parse a token; may raise ParseError
|
| 39 |
+
break
|
| 40 |
+
root = p.rootnode # root of abstract syntax tree
|
| 41 |
+
|
| 42 |
+
A Parser instance may be reused by calling setup() repeatedly.
|
| 43 |
+
|
| 44 |
+
A Parser instance contains state pertaining to the current token
|
| 45 |
+
sequence, and should not be used concurrently by different threads
|
| 46 |
+
to parse separate token sequences.
|
| 47 |
+
|
| 48 |
+
See driver.py for how to get input tokens by tokenizing a file or
|
| 49 |
+
string.
|
| 50 |
+
|
| 51 |
+
Parsing is complete when addtoken() returns True; the root of the
|
| 52 |
+
abstract syntax tree can then be retrieved from the rootnode
|
| 53 |
+
instance variable. When a syntax error occurs, addtoken() raises
|
| 54 |
+
the ParseError exception. There is no error recovery; the parser
|
| 55 |
+
cannot be used after a syntax error was reported (but it can be
|
| 56 |
+
reinitialized by calling setup()).
|
| 57 |
+
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, grammar, convert=None):
|
| 61 |
+
"""Constructor.
|
| 62 |
+
|
| 63 |
+
The grammar argument is a grammar.Grammar instance; see the
|
| 64 |
+
grammar module for more information.
|
| 65 |
+
|
| 66 |
+
The parser is not ready yet for parsing; you must call the
|
| 67 |
+
setup() method to get it started.
|
| 68 |
+
|
| 69 |
+
The optional convert argument is a function mapping concrete
|
| 70 |
+
syntax tree nodes to abstract syntax tree nodes. If not
|
| 71 |
+
given, no conversion is done and the syntax tree produced is
|
| 72 |
+
the concrete syntax tree. If given, it must be a function of
|
| 73 |
+
two arguments, the first being the grammar (a grammar.Grammar
|
| 74 |
+
instance), and the second being the concrete syntax tree node
|
| 75 |
+
to be converted. The syntax tree is converted from the bottom
|
| 76 |
+
up.
|
| 77 |
+
|
| 78 |
+
A concrete syntax tree node is a (type, value, context, nodes)
|
| 79 |
+
tuple, where type is the node type (a token or symbol number),
|
| 80 |
+
value is None for symbols and a string for tokens, context is
|
| 81 |
+
None or an opaque value used for error reporting (typically a
|
| 82 |
+
(lineno, offset) pair), and nodes is a list of children for
|
| 83 |
+
symbols, and None for tokens.
|
| 84 |
+
|
| 85 |
+
An abstract syntax tree node may be anything; this is entirely
|
| 86 |
+
up to the converter function.
|
| 87 |
+
|
| 88 |
+
"""
|
| 89 |
+
self.grammar = grammar
|
| 90 |
+
self.convert = convert or (lambda grammar, node: node)
|
| 91 |
+
|
| 92 |
+
def setup(self, start=None):
|
| 93 |
+
"""Prepare for parsing.
|
| 94 |
+
|
| 95 |
+
This *must* be called before starting to parse.
|
| 96 |
+
|
| 97 |
+
The optional argument is an alternative start symbol; it
|
| 98 |
+
defaults to the grammar's start symbol.
|
| 99 |
+
|
| 100 |
+
You can use a Parser instance to parse any number of programs;
|
| 101 |
+
each time you call setup() the parser is reset to an initial
|
| 102 |
+
state determined by the (implicit or explicit) start symbol.
|
| 103 |
+
|
| 104 |
+
"""
|
| 105 |
+
if start is None:
|
| 106 |
+
start = self.grammar.start
|
| 107 |
+
# Each stack entry is a tuple: (dfa, state, node).
|
| 108 |
+
# A node is a tuple: (type, value, context, children),
|
| 109 |
+
# where children is a list of nodes or None, and context may be None.
|
| 110 |
+
newnode = (start, None, None, [])
|
| 111 |
+
stackentry = (self.grammar.dfas[start], 0, newnode)
|
| 112 |
+
self.stack = [stackentry]
|
| 113 |
+
self.rootnode = None
|
| 114 |
+
self.used_names = set() # Aliased to self.rootnode.used_names in pop()
|
| 115 |
+
|
| 116 |
+
def addtoken(self, type, value, context):
|
| 117 |
+
"""Add a token; return True iff this is the end of the program."""
|
| 118 |
+
# Map from token to label
|
| 119 |
+
ilabel = self.classify(type, value, context)
|
| 120 |
+
# Loop until the token is shifted; may raise exceptions
|
| 121 |
+
while True:
|
| 122 |
+
dfa, state, node = self.stack[-1]
|
| 123 |
+
states, first = dfa
|
| 124 |
+
arcs = states[state]
|
| 125 |
+
# Look for a state with this label
|
| 126 |
+
for i, newstate in arcs:
|
| 127 |
+
t, v = self.grammar.labels[i]
|
| 128 |
+
if ilabel == i:
|
| 129 |
+
# Look it up in the list of labels
|
| 130 |
+
assert t < 256
|
| 131 |
+
# Shift a token; we're done with it
|
| 132 |
+
self.shift(type, value, newstate, context)
|
| 133 |
+
# Pop while we are in an accept-only state
|
| 134 |
+
state = newstate
|
| 135 |
+
while states[state] == [(0, state)]:
|
| 136 |
+
self.pop()
|
| 137 |
+
if not self.stack:
|
| 138 |
+
# Done parsing!
|
| 139 |
+
return True
|
| 140 |
+
dfa, state, node = self.stack[-1]
|
| 141 |
+
states, first = dfa
|
| 142 |
+
# Done with this token
|
| 143 |
+
return False
|
| 144 |
+
elif t >= 256:
|
| 145 |
+
# See if it's a symbol and if we're in its first set
|
| 146 |
+
itsdfa = self.grammar.dfas[t]
|
| 147 |
+
itsstates, itsfirst = itsdfa
|
| 148 |
+
if ilabel in itsfirst:
|
| 149 |
+
# Push a symbol
|
| 150 |
+
self.push(t, self.grammar.dfas[t], newstate, context)
|
| 151 |
+
break # To continue the outer while loop
|
| 152 |
+
else:
|
| 153 |
+
if (0, state) in arcs:
|
| 154 |
+
# An accepting state, pop it and try something else
|
| 155 |
+
self.pop()
|
| 156 |
+
if not self.stack:
|
| 157 |
+
# Done parsing, but another token is input
|
| 158 |
+
raise ParseError("too much input",
|
| 159 |
+
type, value, context)
|
| 160 |
+
else:
|
| 161 |
+
# No success finding a transition
|
| 162 |
+
raise ParseError("bad input", type, value, context)
|
| 163 |
+
|
| 164 |
+
def classify(self, type, value, context):
|
| 165 |
+
"""Turn a token into a label. (Internal)"""
|
| 166 |
+
if type == token.NAME:
|
| 167 |
+
# Keep a listing of all used names
|
| 168 |
+
self.used_names.add(value)
|
| 169 |
+
# Check for reserved words
|
| 170 |
+
ilabel = self.grammar.keywords.get(value)
|
| 171 |
+
if ilabel is not None:
|
| 172 |
+
return ilabel
|
| 173 |
+
ilabel = self.grammar.tokens.get(type)
|
| 174 |
+
if ilabel is None:
|
| 175 |
+
raise ParseError("bad token", type, value, context)
|
| 176 |
+
return ilabel
|
| 177 |
+
|
| 178 |
+
def shift(self, type, value, newstate, context):
|
| 179 |
+
"""Shift a token. (Internal)"""
|
| 180 |
+
dfa, state, node = self.stack[-1]
|
| 181 |
+
newnode = (type, value, context, None)
|
| 182 |
+
newnode = self.convert(self.grammar, newnode)
|
| 183 |
+
if newnode is not None:
|
| 184 |
+
node[-1].append(newnode)
|
| 185 |
+
self.stack[-1] = (dfa, newstate, node)
|
| 186 |
+
|
| 187 |
+
def push(self, type, newdfa, newstate, context):
|
| 188 |
+
"""Push a nonterminal. (Internal)"""
|
| 189 |
+
dfa, state, node = self.stack[-1]
|
| 190 |
+
newnode = (type, None, context, [])
|
| 191 |
+
self.stack[-1] = (dfa, newstate, node)
|
| 192 |
+
self.stack.append((newdfa, 0, newnode))
|
| 193 |
+
|
| 194 |
+
def pop(self):
|
| 195 |
+
"""Pop a nonterminal. (Internal)"""
|
| 196 |
+
popdfa, popstate, popnode = self.stack.pop()
|
| 197 |
+
newnode = self.convert(self.grammar, popnode)
|
| 198 |
+
if newnode is not None:
|
| 199 |
+
if self.stack:
|
| 200 |
+
dfa, state, node = self.stack[-1]
|
| 201 |
+
node[-1].append(newnode)
|
| 202 |
+
else:
|
| 203 |
+
self.rootnode = newnode
|
| 204 |
+
self.rootnode.used_names = self.used_names
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/pgen.py
ADD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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
# Pgen imports
|
| 5 |
+
from . import grammar, token, tokenize
|
| 6 |
+
|
| 7 |
+
class PgenGrammar(grammar.Grammar):
|
| 8 |
+
pass
|
| 9 |
+
|
| 10 |
+
class ParserGenerator(object):
|
| 11 |
+
|
| 12 |
+
def __init__(self, filename, stream=None):
|
| 13 |
+
close_stream = None
|
| 14 |
+
if stream is None:
|
| 15 |
+
stream = open(filename, encoding="utf-8")
|
| 16 |
+
close_stream = stream.close
|
| 17 |
+
self.filename = filename
|
| 18 |
+
self.stream = stream
|
| 19 |
+
self.generator = tokenize.generate_tokens(stream.readline)
|
| 20 |
+
self.gettoken() # Initialize lookahead
|
| 21 |
+
self.dfas, self.startsymbol = self.parse()
|
| 22 |
+
if close_stream is not None:
|
| 23 |
+
close_stream()
|
| 24 |
+
self.first = {} # map from symbol name to set of tokens
|
| 25 |
+
self.addfirstsets()
|
| 26 |
+
|
| 27 |
+
def make_grammar(self):
|
| 28 |
+
c = PgenGrammar()
|
| 29 |
+
names = list(self.dfas.keys())
|
| 30 |
+
names.sort()
|
| 31 |
+
names.remove(self.startsymbol)
|
| 32 |
+
names.insert(0, self.startsymbol)
|
| 33 |
+
for name in names:
|
| 34 |
+
i = 256 + len(c.symbol2number)
|
| 35 |
+
c.symbol2number[name] = i
|
| 36 |
+
c.number2symbol[i] = name
|
| 37 |
+
for name in names:
|
| 38 |
+
dfa = self.dfas[name]
|
| 39 |
+
states = []
|
| 40 |
+
for state in dfa:
|
| 41 |
+
arcs = []
|
| 42 |
+
for label, next in sorted(state.arcs.items()):
|
| 43 |
+
arcs.append((self.make_label(c, label), dfa.index(next)))
|
| 44 |
+
if state.isfinal:
|
| 45 |
+
arcs.append((0, dfa.index(state)))
|
| 46 |
+
states.append(arcs)
|
| 47 |
+
c.states.append(states)
|
| 48 |
+
c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name))
|
| 49 |
+
c.start = c.symbol2number[self.startsymbol]
|
| 50 |
+
return c
|
| 51 |
+
|
| 52 |
+
def make_first(self, c, name):
|
| 53 |
+
rawfirst = self.first[name]
|
| 54 |
+
first = {}
|
| 55 |
+
for label in sorted(rawfirst):
|
| 56 |
+
ilabel = self.make_label(c, label)
|
| 57 |
+
##assert ilabel not in first # XXX failed on <> ... !=
|
| 58 |
+
first[ilabel] = 1
|
| 59 |
+
return first
|
| 60 |
+
|
| 61 |
+
def make_label(self, c, label):
|
| 62 |
+
# XXX Maybe this should be a method on a subclass of converter?
|
| 63 |
+
ilabel = len(c.labels)
|
| 64 |
+
if label[0].isalpha():
|
| 65 |
+
# Either a symbol name or a named token
|
| 66 |
+
if label in c.symbol2number:
|
| 67 |
+
# A symbol name (a non-terminal)
|
| 68 |
+
if label in c.symbol2label:
|
| 69 |
+
return c.symbol2label[label]
|
| 70 |
+
else:
|
| 71 |
+
c.labels.append((c.symbol2number[label], None))
|
| 72 |
+
c.symbol2label[label] = ilabel
|
| 73 |
+
return ilabel
|
| 74 |
+
else:
|
| 75 |
+
# A named token (NAME, NUMBER, STRING)
|
| 76 |
+
itoken = getattr(token, label, None)
|
| 77 |
+
assert isinstance(itoken, int), label
|
| 78 |
+
assert itoken in token.tok_name, label
|
| 79 |
+
if itoken in c.tokens:
|
| 80 |
+
return c.tokens[itoken]
|
| 81 |
+
else:
|
| 82 |
+
c.labels.append((itoken, None))
|
| 83 |
+
c.tokens[itoken] = ilabel
|
| 84 |
+
return ilabel
|
| 85 |
+
else:
|
| 86 |
+
# Either a keyword or an operator
|
| 87 |
+
assert label[0] in ('"', "'"), label
|
| 88 |
+
value = eval(label)
|
| 89 |
+
if value[0].isalpha():
|
| 90 |
+
# A keyword
|
| 91 |
+
if value in c.keywords:
|
| 92 |
+
return c.keywords[value]
|
| 93 |
+
else:
|
| 94 |
+
c.labels.append((token.NAME, value))
|
| 95 |
+
c.keywords[value] = ilabel
|
| 96 |
+
return ilabel
|
| 97 |
+
else:
|
| 98 |
+
# An operator (any non-numeric token)
|
| 99 |
+
itoken = grammar.opmap[value] # Fails if unknown token
|
| 100 |
+
if itoken in c.tokens:
|
| 101 |
+
return c.tokens[itoken]
|
| 102 |
+
else:
|
| 103 |
+
c.labels.append((itoken, None))
|
| 104 |
+
c.tokens[itoken] = ilabel
|
| 105 |
+
return ilabel
|
| 106 |
+
|
| 107 |
+
def addfirstsets(self):
|
| 108 |
+
names = list(self.dfas.keys())
|
| 109 |
+
names.sort()
|
| 110 |
+
for name in names:
|
| 111 |
+
if name not in self.first:
|
| 112 |
+
self.calcfirst(name)
|
| 113 |
+
#print name, self.first[name].keys()
|
| 114 |
+
|
| 115 |
+
def calcfirst(self, name):
|
| 116 |
+
dfa = self.dfas[name]
|
| 117 |
+
self.first[name] = None # dummy to detect left recursion
|
| 118 |
+
state = dfa[0]
|
| 119 |
+
totalset = {}
|
| 120 |
+
overlapcheck = {}
|
| 121 |
+
for label, next in state.arcs.items():
|
| 122 |
+
if label in self.dfas:
|
| 123 |
+
if label in self.first:
|
| 124 |
+
fset = self.first[label]
|
| 125 |
+
if fset is None:
|
| 126 |
+
raise ValueError("recursion for rule %r" % name)
|
| 127 |
+
else:
|
| 128 |
+
self.calcfirst(label)
|
| 129 |
+
fset = self.first[label]
|
| 130 |
+
totalset.update(fset)
|
| 131 |
+
overlapcheck[label] = fset
|
| 132 |
+
else:
|
| 133 |
+
totalset[label] = 1
|
| 134 |
+
overlapcheck[label] = {label: 1}
|
| 135 |
+
inverse = {}
|
| 136 |
+
for label, itsfirst in overlapcheck.items():
|
| 137 |
+
for symbol in itsfirst:
|
| 138 |
+
if symbol in inverse:
|
| 139 |
+
raise ValueError("rule %s is ambiguous; %s is in the"
|
| 140 |
+
" first sets of %s as well as %s" %
|
| 141 |
+
(name, symbol, label, inverse[symbol]))
|
| 142 |
+
inverse[symbol] = label
|
| 143 |
+
self.first[name] = totalset
|
| 144 |
+
|
| 145 |
+
def parse(self):
|
| 146 |
+
dfas = {}
|
| 147 |
+
startsymbol = None
|
| 148 |
+
# MSTART: (NEWLINE | RULE)* ENDMARKER
|
| 149 |
+
while self.type != token.ENDMARKER:
|
| 150 |
+
while self.type == token.NEWLINE:
|
| 151 |
+
self.gettoken()
|
| 152 |
+
# RULE: NAME ':' RHS NEWLINE
|
| 153 |
+
name = self.expect(token.NAME)
|
| 154 |
+
self.expect(token.OP, ":")
|
| 155 |
+
a, z = self.parse_rhs()
|
| 156 |
+
self.expect(token.NEWLINE)
|
| 157 |
+
#self.dump_nfa(name, a, z)
|
| 158 |
+
dfa = self.make_dfa(a, z)
|
| 159 |
+
#self.dump_dfa(name, dfa)
|
| 160 |
+
oldlen = len(dfa)
|
| 161 |
+
self.simplify_dfa(dfa)
|
| 162 |
+
newlen = len(dfa)
|
| 163 |
+
dfas[name] = dfa
|
| 164 |
+
#print name, oldlen, newlen
|
| 165 |
+
if startsymbol is None:
|
| 166 |
+
startsymbol = name
|
| 167 |
+
return dfas, startsymbol
|
| 168 |
+
|
| 169 |
+
def make_dfa(self, start, finish):
|
| 170 |
+
# To turn an NFA into a DFA, we define the states of the DFA
|
| 171 |
+
# to correspond to *sets* of states of the NFA. Then do some
|
| 172 |
+
# state reduction. Let's represent sets as dicts with 1 for
|
| 173 |
+
# values.
|
| 174 |
+
assert isinstance(start, NFAState)
|
| 175 |
+
assert isinstance(finish, NFAState)
|
| 176 |
+
def closure(state):
|
| 177 |
+
base = {}
|
| 178 |
+
addclosure(state, base)
|
| 179 |
+
return base
|
| 180 |
+
def addclosure(state, base):
|
| 181 |
+
assert isinstance(state, NFAState)
|
| 182 |
+
if state in base:
|
| 183 |
+
return
|
| 184 |
+
base[state] = 1
|
| 185 |
+
for label, next in state.arcs:
|
| 186 |
+
if label is None:
|
| 187 |
+
addclosure(next, base)
|
| 188 |
+
states = [DFAState(closure(start), finish)]
|
| 189 |
+
for state in states: # NB states grows while we're iterating
|
| 190 |
+
arcs = {}
|
| 191 |
+
for nfastate in state.nfaset:
|
| 192 |
+
for label, next in nfastate.arcs:
|
| 193 |
+
if label is not None:
|
| 194 |
+
addclosure(next, arcs.setdefault(label, {}))
|
| 195 |
+
for label, nfaset in sorted(arcs.items()):
|
| 196 |
+
for st in states:
|
| 197 |
+
if st.nfaset == nfaset:
|
| 198 |
+
break
|
| 199 |
+
else:
|
| 200 |
+
st = DFAState(nfaset, finish)
|
| 201 |
+
states.append(st)
|
| 202 |
+
state.addarc(st, label)
|
| 203 |
+
return states # List of DFAState instances; first one is start
|
| 204 |
+
|
| 205 |
+
def dump_nfa(self, name, start, finish):
|
| 206 |
+
print("Dump of NFA for", name)
|
| 207 |
+
todo = [start]
|
| 208 |
+
for i, state in enumerate(todo):
|
| 209 |
+
print(" State", i, state is finish and "(final)" or "")
|
| 210 |
+
for label, next in state.arcs:
|
| 211 |
+
if next in todo:
|
| 212 |
+
j = todo.index(next)
|
| 213 |
+
else:
|
| 214 |
+
j = len(todo)
|
| 215 |
+
todo.append(next)
|
| 216 |
+
if label is None:
|
| 217 |
+
print(" -> %d" % j)
|
| 218 |
+
else:
|
| 219 |
+
print(" %s -> %d" % (label, j))
|
| 220 |
+
|
| 221 |
+
def dump_dfa(self, name, dfa):
|
| 222 |
+
print("Dump of DFA for", name)
|
| 223 |
+
for i, state in enumerate(dfa):
|
| 224 |
+
print(" State", i, state.isfinal and "(final)" or "")
|
| 225 |
+
for label, next in sorted(state.arcs.items()):
|
| 226 |
+
print(" %s -> %d" % (label, dfa.index(next)))
|
| 227 |
+
|
| 228 |
+
def simplify_dfa(self, dfa):
|
| 229 |
+
# This is not theoretically optimal, but works well enough.
|
| 230 |
+
# Algorithm: repeatedly look for two states that have the same
|
| 231 |
+
# set of arcs (same labels pointing to the same nodes) and
|
| 232 |
+
# unify them, until things stop changing.
|
| 233 |
+
|
| 234 |
+
# dfa is a list of DFAState instances
|
| 235 |
+
changes = True
|
| 236 |
+
while changes:
|
| 237 |
+
changes = False
|
| 238 |
+
for i, state_i in enumerate(dfa):
|
| 239 |
+
for j in range(i+1, len(dfa)):
|
| 240 |
+
state_j = dfa[j]
|
| 241 |
+
if state_i == state_j:
|
| 242 |
+
#print " unify", i, j
|
| 243 |
+
del dfa[j]
|
| 244 |
+
for state in dfa:
|
| 245 |
+
state.unifystate(state_j, state_i)
|
| 246 |
+
changes = True
|
| 247 |
+
break
|
| 248 |
+
|
| 249 |
+
def parse_rhs(self):
|
| 250 |
+
# RHS: ALT ('|' ALT)*
|
| 251 |
+
a, z = self.parse_alt()
|
| 252 |
+
if self.value != "|":
|
| 253 |
+
return a, z
|
| 254 |
+
else:
|
| 255 |
+
aa = NFAState()
|
| 256 |
+
zz = NFAState()
|
| 257 |
+
aa.addarc(a)
|
| 258 |
+
z.addarc(zz)
|
| 259 |
+
while self.value == "|":
|
| 260 |
+
self.gettoken()
|
| 261 |
+
a, z = self.parse_alt()
|
| 262 |
+
aa.addarc(a)
|
| 263 |
+
z.addarc(zz)
|
| 264 |
+
return aa, zz
|
| 265 |
+
|
| 266 |
+
def parse_alt(self):
|
| 267 |
+
# ALT: ITEM+
|
| 268 |
+
a, b = self.parse_item()
|
| 269 |
+
while (self.value in ("(", "[") or
|
| 270 |
+
self.type in (token.NAME, token.STRING)):
|
| 271 |
+
c, d = self.parse_item()
|
| 272 |
+
b.addarc(c)
|
| 273 |
+
b = d
|
| 274 |
+
return a, b
|
| 275 |
+
|
| 276 |
+
def parse_item(self):
|
| 277 |
+
# ITEM: '[' RHS ']' | ATOM ['+' | '*']
|
| 278 |
+
if self.value == "[":
|
| 279 |
+
self.gettoken()
|
| 280 |
+
a, z = self.parse_rhs()
|
| 281 |
+
self.expect(token.OP, "]")
|
| 282 |
+
a.addarc(z)
|
| 283 |
+
return a, z
|
| 284 |
+
else:
|
| 285 |
+
a, z = self.parse_atom()
|
| 286 |
+
value = self.value
|
| 287 |
+
if value not in ("+", "*"):
|
| 288 |
+
return a, z
|
| 289 |
+
self.gettoken()
|
| 290 |
+
z.addarc(a)
|
| 291 |
+
if value == "+":
|
| 292 |
+
return a, z
|
| 293 |
+
else:
|
| 294 |
+
return a, a
|
| 295 |
+
|
| 296 |
+
def parse_atom(self):
|
| 297 |
+
# ATOM: '(' RHS ')' | NAME | STRING
|
| 298 |
+
if self.value == "(":
|
| 299 |
+
self.gettoken()
|
| 300 |
+
a, z = self.parse_rhs()
|
| 301 |
+
self.expect(token.OP, ")")
|
| 302 |
+
return a, z
|
| 303 |
+
elif self.type in (token.NAME, token.STRING):
|
| 304 |
+
a = NFAState()
|
| 305 |
+
z = NFAState()
|
| 306 |
+
a.addarc(z, self.value)
|
| 307 |
+
self.gettoken()
|
| 308 |
+
return a, z
|
| 309 |
+
else:
|
| 310 |
+
self.raise_error("expected (...) or NAME or STRING, got %s/%s",
|
| 311 |
+
self.type, self.value)
|
| 312 |
+
|
| 313 |
+
def expect(self, type, value=None):
|
| 314 |
+
if self.type != type or (value is not None and self.value != value):
|
| 315 |
+
self.raise_error("expected %s/%s, got %s/%s",
|
| 316 |
+
type, value, self.type, self.value)
|
| 317 |
+
value = self.value
|
| 318 |
+
self.gettoken()
|
| 319 |
+
return value
|
| 320 |
+
|
| 321 |
+
def gettoken(self):
|
| 322 |
+
tup = next(self.generator)
|
| 323 |
+
while tup[0] in (tokenize.COMMENT, tokenize.NL):
|
| 324 |
+
tup = next(self.generator)
|
| 325 |
+
self.type, self.value, self.begin, self.end, self.line = tup
|
| 326 |
+
#print token.tok_name[self.type], repr(self.value)
|
| 327 |
+
|
| 328 |
+
def raise_error(self, msg, *args):
|
| 329 |
+
if args:
|
| 330 |
+
try:
|
| 331 |
+
msg = msg % args
|
| 332 |
+
except:
|
| 333 |
+
msg = " ".join([msg] + list(map(str, args)))
|
| 334 |
+
raise SyntaxError(msg, (self.filename, self.end[0],
|
| 335 |
+
self.end[1], self.line))
|
| 336 |
+
|
| 337 |
+
class NFAState(object):
|
| 338 |
+
|
| 339 |
+
def __init__(self):
|
| 340 |
+
self.arcs = [] # list of (label, NFAState) pairs
|
| 341 |
+
|
| 342 |
+
def addarc(self, next, label=None):
|
| 343 |
+
assert label is None or isinstance(label, str)
|
| 344 |
+
assert isinstance(next, NFAState)
|
| 345 |
+
self.arcs.append((label, next))
|
| 346 |
+
|
| 347 |
+
class DFAState(object):
|
| 348 |
+
|
| 349 |
+
def __init__(self, nfaset, final):
|
| 350 |
+
assert isinstance(nfaset, dict)
|
| 351 |
+
assert isinstance(next(iter(nfaset)), NFAState)
|
| 352 |
+
assert isinstance(final, NFAState)
|
| 353 |
+
self.nfaset = nfaset
|
| 354 |
+
self.isfinal = final in nfaset
|
| 355 |
+
self.arcs = {} # map from label to DFAState
|
| 356 |
+
|
| 357 |
+
def addarc(self, next, label):
|
| 358 |
+
assert isinstance(label, str)
|
| 359 |
+
assert label not in self.arcs
|
| 360 |
+
assert isinstance(next, DFAState)
|
| 361 |
+
self.arcs[label] = next
|
| 362 |
+
|
| 363 |
+
def unifystate(self, old, new):
|
| 364 |
+
for label, next in self.arcs.items():
|
| 365 |
+
if next is old:
|
| 366 |
+
self.arcs[label] = new
|
| 367 |
+
|
| 368 |
+
def __eq__(self, other):
|
| 369 |
+
# Equality test -- ignore the nfaset instance variable
|
| 370 |
+
assert isinstance(other, DFAState)
|
| 371 |
+
if self.isfinal != other.isfinal:
|
| 372 |
+
return False
|
| 373 |
+
# Can't just return self.arcs == other.arcs, because that
|
| 374 |
+
# would invoke this method recursively, with cycles...
|
| 375 |
+
if len(self.arcs) != len(other.arcs):
|
| 376 |
+
return False
|
| 377 |
+
for label, next in self.arcs.items():
|
| 378 |
+
if next is not other.arcs.get(label):
|
| 379 |
+
return False
|
| 380 |
+
return True
|
| 381 |
+
|
| 382 |
+
__hash__ = None # For Py3 compatibility.
|
| 383 |
+
|
| 384 |
+
def generate_grammar(filename="Grammar.txt"):
|
| 385 |
+
p = ParserGenerator(filename)
|
| 386 |
+
return p.make_grammar()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/token.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#! /usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
"""Token constants (from "token.h")."""
|
| 4 |
+
|
| 5 |
+
# Taken from Python (r53757) and modified to include some tokens
|
| 6 |
+
# originally monkeypatched in by pgen2.tokenize
|
| 7 |
+
|
| 8 |
+
#--start constants--
|
| 9 |
+
ENDMARKER = 0
|
| 10 |
+
NAME = 1
|
| 11 |
+
NUMBER = 2
|
| 12 |
+
STRING = 3
|
| 13 |
+
NEWLINE = 4
|
| 14 |
+
INDENT = 5
|
| 15 |
+
DEDENT = 6
|
| 16 |
+
LPAR = 7
|
| 17 |
+
RPAR = 8
|
| 18 |
+
LSQB = 9
|
| 19 |
+
RSQB = 10
|
| 20 |
+
COLON = 11
|
| 21 |
+
COMMA = 12
|
| 22 |
+
SEMI = 13
|
| 23 |
+
PLUS = 14
|
| 24 |
+
MINUS = 15
|
| 25 |
+
STAR = 16
|
| 26 |
+
SLASH = 17
|
| 27 |
+
VBAR = 18
|
| 28 |
+
AMPER = 19
|
| 29 |
+
LESS = 20
|
| 30 |
+
GREATER = 21
|
| 31 |
+
EQUAL = 22
|
| 32 |
+
DOT = 23
|
| 33 |
+
PERCENT = 24
|
| 34 |
+
BACKQUOTE = 25
|
| 35 |
+
LBRACE = 26
|
| 36 |
+
RBRACE = 27
|
| 37 |
+
EQEQUAL = 28
|
| 38 |
+
NOTEQUAL = 29
|
| 39 |
+
LESSEQUAL = 30
|
| 40 |
+
GREATEREQUAL = 31
|
| 41 |
+
TILDE = 32
|
| 42 |
+
CIRCUMFLEX = 33
|
| 43 |
+
LEFTSHIFT = 34
|
| 44 |
+
RIGHTSHIFT = 35
|
| 45 |
+
DOUBLESTAR = 36
|
| 46 |
+
PLUSEQUAL = 37
|
| 47 |
+
MINEQUAL = 38
|
| 48 |
+
STAREQUAL = 39
|
| 49 |
+
SLASHEQUAL = 40
|
| 50 |
+
PERCENTEQUAL = 41
|
| 51 |
+
AMPEREQUAL = 42
|
| 52 |
+
VBAREQUAL = 43
|
| 53 |
+
CIRCUMFLEXEQUAL = 44
|
| 54 |
+
LEFTSHIFTEQUAL = 45
|
| 55 |
+
RIGHTSHIFTEQUAL = 46
|
| 56 |
+
DOUBLESTAREQUAL = 47
|
| 57 |
+
DOUBLESLASH = 48
|
| 58 |
+
DOUBLESLASHEQUAL = 49
|
| 59 |
+
AT = 50
|
| 60 |
+
ATEQUAL = 51
|
| 61 |
+
OP = 52
|
| 62 |
+
COMMENT = 53
|
| 63 |
+
NL = 54
|
| 64 |
+
RARROW = 55
|
| 65 |
+
AWAIT = 56
|
| 66 |
+
ASYNC = 57
|
| 67 |
+
ERRORTOKEN = 58
|
| 68 |
+
COLONEQUAL = 59
|
| 69 |
+
N_TOKENS = 60
|
| 70 |
+
NT_OFFSET = 256
|
| 71 |
+
#--end constants--
|
| 72 |
+
|
| 73 |
+
tok_name = {}
|
| 74 |
+
for _name, _value in list(globals().items()):
|
| 75 |
+
if type(_value) is type(0):
|
| 76 |
+
tok_name[_value] = _name
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def ISTERMINAL(x):
|
| 80 |
+
return x < NT_OFFSET
|
| 81 |
+
|
| 82 |
+
def ISNONTERMINAL(x):
|
| 83 |
+
return x >= NT_OFFSET
|
| 84 |
+
|
| 85 |
+
def ISEOF(x):
|
| 86 |
+
return x == ENDMARKER
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/pgen2/tokenize.py
ADDED
|
@@ -0,0 +1,564 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
|
| 4 |
+
"""Tokenization help for Python programs.
|
| 5 |
+
|
| 6 |
+
generate_tokens(readline) is a generator that breaks a stream of
|
| 7 |
+
text into Python tokens. It accepts a readline-like method which is called
|
| 8 |
+
repeatedly to get the next line of input (or "" for EOF). It generates
|
| 9 |
+
5-tuples with these members:
|
| 10 |
+
|
| 11 |
+
the token type (see token.py)
|
| 12 |
+
the token (a string)
|
| 13 |
+
the starting (row, column) indices of the token (a 2-tuple of ints)
|
| 14 |
+
the ending (row, column) indices of the token (a 2-tuple of ints)
|
| 15 |
+
the original line (string)
|
| 16 |
+
|
| 17 |
+
It is designed to match the working of the Python tokenizer exactly, except
|
| 18 |
+
that it produces COMMENT tokens for comments and gives type OP for all
|
| 19 |
+
operators
|
| 20 |
+
|
| 21 |
+
Older entry points
|
| 22 |
+
tokenize_loop(readline, tokeneater)
|
| 23 |
+
tokenize(readline, tokeneater=printtoken)
|
| 24 |
+
are the same, except instead of generating tokens, tokeneater is a callback
|
| 25 |
+
function to which the 5 fields described above are passed as 5 arguments,
|
| 26 |
+
each time a new token is found."""
|
| 27 |
+
|
| 28 |
+
__author__ = 'Ka-Ping Yee <ping@lfw.org>'
|
| 29 |
+
__credits__ = \
|
| 30 |
+
'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro'
|
| 31 |
+
|
| 32 |
+
import string, re
|
| 33 |
+
from codecs import BOM_UTF8, lookup
|
| 34 |
+
from lib2to3.pgen2.token import *
|
| 35 |
+
|
| 36 |
+
from . import token
|
| 37 |
+
__all__ = [x for x in dir(token) if x[0] != '_'] + ["tokenize",
|
| 38 |
+
"generate_tokens", "untokenize"]
|
| 39 |
+
del token
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
bytes
|
| 43 |
+
except NameError:
|
| 44 |
+
# Support bytes type in Python <= 2.5, so 2to3 turns itself into
|
| 45 |
+
# valid Python 3 code.
|
| 46 |
+
bytes = str
|
| 47 |
+
|
| 48 |
+
def group(*choices): return '(' + '|'.join(choices) + ')'
|
| 49 |
+
def any(*choices): return group(*choices) + '*'
|
| 50 |
+
def maybe(*choices): return group(*choices) + '?'
|
| 51 |
+
def _combinations(*l):
|
| 52 |
+
return set(
|
| 53 |
+
x + y for x in l for y in l + ("",) if x.casefold() != y.casefold()
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
Whitespace = r'[ \f\t]*'
|
| 57 |
+
Comment = r'#[^\r\n]*'
|
| 58 |
+
Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
|
| 59 |
+
Name = r'\w+'
|
| 60 |
+
|
| 61 |
+
Binnumber = r'0[bB]_?[01]+(?:_[01]+)*'
|
| 62 |
+
Hexnumber = r'0[xX]_?[\da-fA-F]+(?:_[\da-fA-F]+)*[lL]?'
|
| 63 |
+
Octnumber = r'0[oO]?_?[0-7]+(?:_[0-7]+)*[lL]?'
|
| 64 |
+
Decnumber = group(r'[1-9]\d*(?:_\d+)*[lL]?', '0[lL]?')
|
| 65 |
+
Intnumber = group(Binnumber, Hexnumber, Octnumber, Decnumber)
|
| 66 |
+
Exponent = r'[eE][-+]?\d+(?:_\d+)*'
|
| 67 |
+
Pointfloat = group(r'\d+(?:_\d+)*\.(?:\d+(?:_\d+)*)?', r'\.\d+(?:_\d+)*') + maybe(Exponent)
|
| 68 |
+
Expfloat = r'\d+(?:_\d+)*' + Exponent
|
| 69 |
+
Floatnumber = group(Pointfloat, Expfloat)
|
| 70 |
+
Imagnumber = group(r'\d+(?:_\d+)*[jJ]', Floatnumber + r'[jJ]')
|
| 71 |
+
Number = group(Imagnumber, Floatnumber, Intnumber)
|
| 72 |
+
|
| 73 |
+
# Tail end of ' string.
|
| 74 |
+
Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
|
| 75 |
+
# Tail end of " string.
|
| 76 |
+
Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
|
| 77 |
+
# Tail end of ''' string.
|
| 78 |
+
Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
|
| 79 |
+
# Tail end of """ string.
|
| 80 |
+
Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
|
| 81 |
+
_litprefix = r"(?:[uUrRbBfF]|[rR][fFbB]|[fFbBuU][rR])?"
|
| 82 |
+
Triple = group(_litprefix + "'''", _litprefix + '"""')
|
| 83 |
+
# Single-line ' or " string.
|
| 84 |
+
String = group(_litprefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
|
| 85 |
+
_litprefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
|
| 86 |
+
|
| 87 |
+
# Because of leftmost-then-longest match semantics, be sure to put the
|
| 88 |
+
# longest operators first (e.g., if = came before ==, == would get
|
| 89 |
+
# recognized as two instances of =).
|
| 90 |
+
Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
|
| 91 |
+
r"//=?", r"->",
|
| 92 |
+
r"[+\-*/%&@|^=<>]=?",
|
| 93 |
+
r"~")
|
| 94 |
+
|
| 95 |
+
Bracket = '[][(){}]'
|
| 96 |
+
Special = group(r'\r?\n', r':=', r'[:;.,`@]')
|
| 97 |
+
Funny = group(Operator, Bracket, Special)
|
| 98 |
+
|
| 99 |
+
PlainToken = group(Number, Funny, String, Name)
|
| 100 |
+
Token = Ignore + PlainToken
|
| 101 |
+
|
| 102 |
+
# First (or only) line of ' or " string.
|
| 103 |
+
ContStr = group(_litprefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
|
| 104 |
+
group("'", r'\\\r?\n'),
|
| 105 |
+
_litprefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
|
| 106 |
+
group('"', r'\\\r?\n'))
|
| 107 |
+
PseudoExtras = group(r'\\\r?\n', Comment, Triple)
|
| 108 |
+
PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
|
| 109 |
+
|
| 110 |
+
tokenprog, pseudoprog, single3prog, double3prog = map(
|
| 111 |
+
re.compile, (Token, PseudoToken, Single3, Double3))
|
| 112 |
+
|
| 113 |
+
_strprefixes = (
|
| 114 |
+
_combinations('r', 'R', 'f', 'F') |
|
| 115 |
+
_combinations('r', 'R', 'b', 'B') |
|
| 116 |
+
{'u', 'U', 'ur', 'uR', 'Ur', 'UR'}
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
endprogs = {"'": re.compile(Single), '"': re.compile(Double),
|
| 120 |
+
"'''": single3prog, '"""': double3prog,
|
| 121 |
+
**{f"{prefix}'''": single3prog for prefix in _strprefixes},
|
| 122 |
+
**{f'{prefix}"""': double3prog for prefix in _strprefixes},
|
| 123 |
+
**{prefix: None for prefix in _strprefixes}}
|
| 124 |
+
|
| 125 |
+
triple_quoted = (
|
| 126 |
+
{"'''", '"""'} |
|
| 127 |
+
{f"{prefix}'''" for prefix in _strprefixes} |
|
| 128 |
+
{f'{prefix}"""' for prefix in _strprefixes}
|
| 129 |
+
)
|
| 130 |
+
single_quoted = (
|
| 131 |
+
{"'", '"'} |
|
| 132 |
+
{f"{prefix}'" for prefix in _strprefixes} |
|
| 133 |
+
{f'{prefix}"' for prefix in _strprefixes}
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
tabsize = 8
|
| 137 |
+
|
| 138 |
+
class TokenError(Exception): pass
|
| 139 |
+
|
| 140 |
+
class StopTokenizing(Exception): pass
|
| 141 |
+
|
| 142 |
+
def printtoken(type, token, xxx_todo_changeme, xxx_todo_changeme1, line): # for testing
|
| 143 |
+
(srow, scol) = xxx_todo_changeme
|
| 144 |
+
(erow, ecol) = xxx_todo_changeme1
|
| 145 |
+
print("%d,%d-%d,%d:\t%s\t%s" % \
|
| 146 |
+
(srow, scol, erow, ecol, tok_name[type], repr(token)))
|
| 147 |
+
|
| 148 |
+
def tokenize(readline, tokeneater=printtoken):
|
| 149 |
+
"""
|
| 150 |
+
The tokenize() function accepts two parameters: one representing the
|
| 151 |
+
input stream, and one providing an output mechanism for tokenize().
|
| 152 |
+
|
| 153 |
+
The first parameter, readline, must be a callable object which provides
|
| 154 |
+
the same interface as the readline() method of built-in file objects.
|
| 155 |
+
Each call to the function should return one line of input as a string.
|
| 156 |
+
|
| 157 |
+
The second parameter, tokeneater, must also be a callable object. It is
|
| 158 |
+
called once for each token, with five arguments, corresponding to the
|
| 159 |
+
tuples generated by generate_tokens().
|
| 160 |
+
"""
|
| 161 |
+
try:
|
| 162 |
+
tokenize_loop(readline, tokeneater)
|
| 163 |
+
except StopTokenizing:
|
| 164 |
+
pass
|
| 165 |
+
|
| 166 |
+
# backwards compatible interface
|
| 167 |
+
def tokenize_loop(readline, tokeneater):
|
| 168 |
+
for token_info in generate_tokens(readline):
|
| 169 |
+
tokeneater(*token_info)
|
| 170 |
+
|
| 171 |
+
class Untokenizer:
|
| 172 |
+
|
| 173 |
+
def __init__(self):
|
| 174 |
+
self.tokens = []
|
| 175 |
+
self.prev_row = 1
|
| 176 |
+
self.prev_col = 0
|
| 177 |
+
|
| 178 |
+
def add_whitespace(self, start):
|
| 179 |
+
row, col = start
|
| 180 |
+
assert row <= self.prev_row
|
| 181 |
+
col_offset = col - self.prev_col
|
| 182 |
+
if col_offset:
|
| 183 |
+
self.tokens.append(" " * col_offset)
|
| 184 |
+
|
| 185 |
+
def untokenize(self, iterable):
|
| 186 |
+
for t in iterable:
|
| 187 |
+
if len(t) == 2:
|
| 188 |
+
self.compat(t, iterable)
|
| 189 |
+
break
|
| 190 |
+
tok_type, token, start, end, line = t
|
| 191 |
+
self.add_whitespace(start)
|
| 192 |
+
self.tokens.append(token)
|
| 193 |
+
self.prev_row, self.prev_col = end
|
| 194 |
+
if tok_type in (NEWLINE, NL):
|
| 195 |
+
self.prev_row += 1
|
| 196 |
+
self.prev_col = 0
|
| 197 |
+
return "".join(self.tokens)
|
| 198 |
+
|
| 199 |
+
def compat(self, token, iterable):
|
| 200 |
+
startline = False
|
| 201 |
+
indents = []
|
| 202 |
+
toks_append = self.tokens.append
|
| 203 |
+
toknum, tokval = token
|
| 204 |
+
if toknum in (NAME, NUMBER):
|
| 205 |
+
tokval += ' '
|
| 206 |
+
if toknum in (NEWLINE, NL):
|
| 207 |
+
startline = True
|
| 208 |
+
for tok in iterable:
|
| 209 |
+
toknum, tokval = tok[:2]
|
| 210 |
+
|
| 211 |
+
if toknum in (NAME, NUMBER, ASYNC, AWAIT):
|
| 212 |
+
tokval += ' '
|
| 213 |
+
|
| 214 |
+
if toknum == INDENT:
|
| 215 |
+
indents.append(tokval)
|
| 216 |
+
continue
|
| 217 |
+
elif toknum == DEDENT:
|
| 218 |
+
indents.pop()
|
| 219 |
+
continue
|
| 220 |
+
elif toknum in (NEWLINE, NL):
|
| 221 |
+
startline = True
|
| 222 |
+
elif startline and indents:
|
| 223 |
+
toks_append(indents[-1])
|
| 224 |
+
startline = False
|
| 225 |
+
toks_append(tokval)
|
| 226 |
+
|
| 227 |
+
cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
|
| 228 |
+
blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
|
| 229 |
+
|
| 230 |
+
def _get_normal_name(orig_enc):
|
| 231 |
+
"""Imitates get_normal_name in tokenizer.c."""
|
| 232 |
+
# Only care about the first 12 characters.
|
| 233 |
+
enc = orig_enc[:12].lower().replace("_", "-")
|
| 234 |
+
if enc == "utf-8" or enc.startswith("utf-8-"):
|
| 235 |
+
return "utf-8"
|
| 236 |
+
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
|
| 237 |
+
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
|
| 238 |
+
return "iso-8859-1"
|
| 239 |
+
return orig_enc
|
| 240 |
+
|
| 241 |
+
def detect_encoding(readline):
|
| 242 |
+
"""
|
| 243 |
+
The detect_encoding() function is used to detect the encoding that should
|
| 244 |
+
be used to decode a Python source file. It requires one argument, readline,
|
| 245 |
+
in the same way as the tokenize() generator.
|
| 246 |
+
|
| 247 |
+
It will call readline a maximum of twice, and return the encoding used
|
| 248 |
+
(as a string) and a list of any lines (left as bytes) it has read
|
| 249 |
+
in.
|
| 250 |
+
|
| 251 |
+
It detects the encoding from the presence of a utf-8 bom or an encoding
|
| 252 |
+
cookie as specified in pep-0263. If both a bom and a cookie are present, but
|
| 253 |
+
disagree, a SyntaxError will be raised. If the encoding cookie is an invalid
|
| 254 |
+
charset, raise a SyntaxError. Note that if a utf-8 bom is found,
|
| 255 |
+
'utf-8-sig' is returned.
|
| 256 |
+
|
| 257 |
+
If no encoding is specified, then the default of 'utf-8' will be returned.
|
| 258 |
+
"""
|
| 259 |
+
bom_found = False
|
| 260 |
+
encoding = None
|
| 261 |
+
default = 'utf-8'
|
| 262 |
+
def read_or_stop():
|
| 263 |
+
try:
|
| 264 |
+
return readline()
|
| 265 |
+
except StopIteration:
|
| 266 |
+
return bytes()
|
| 267 |
+
|
| 268 |
+
def find_cookie(line):
|
| 269 |
+
try:
|
| 270 |
+
line_string = line.decode('ascii')
|
| 271 |
+
except UnicodeDecodeError:
|
| 272 |
+
return None
|
| 273 |
+
match = cookie_re.match(line_string)
|
| 274 |
+
if not match:
|
| 275 |
+
return None
|
| 276 |
+
encoding = _get_normal_name(match.group(1))
|
| 277 |
+
try:
|
| 278 |
+
codec = lookup(encoding)
|
| 279 |
+
except LookupError:
|
| 280 |
+
# This behaviour mimics the Python interpreter
|
| 281 |
+
raise SyntaxError("unknown encoding: " + encoding)
|
| 282 |
+
|
| 283 |
+
if bom_found:
|
| 284 |
+
if codec.name != 'utf-8':
|
| 285 |
+
# This behaviour mimics the Python interpreter
|
| 286 |
+
raise SyntaxError('encoding problem: utf-8')
|
| 287 |
+
encoding += '-sig'
|
| 288 |
+
return encoding
|
| 289 |
+
|
| 290 |
+
first = read_or_stop()
|
| 291 |
+
if first.startswith(BOM_UTF8):
|
| 292 |
+
bom_found = True
|
| 293 |
+
first = first[3:]
|
| 294 |
+
default = 'utf-8-sig'
|
| 295 |
+
if not first:
|
| 296 |
+
return default, []
|
| 297 |
+
|
| 298 |
+
encoding = find_cookie(first)
|
| 299 |
+
if encoding:
|
| 300 |
+
return encoding, [first]
|
| 301 |
+
if not blank_re.match(first):
|
| 302 |
+
return default, [first]
|
| 303 |
+
|
| 304 |
+
second = read_or_stop()
|
| 305 |
+
if not second:
|
| 306 |
+
return default, [first]
|
| 307 |
+
|
| 308 |
+
encoding = find_cookie(second)
|
| 309 |
+
if encoding:
|
| 310 |
+
return encoding, [first, second]
|
| 311 |
+
|
| 312 |
+
return default, [first, second]
|
| 313 |
+
|
| 314 |
+
def untokenize(iterable):
|
| 315 |
+
"""Transform tokens back into Python source code.
|
| 316 |
+
|
| 317 |
+
Each element returned by the iterable must be a token sequence
|
| 318 |
+
with at least two elements, a token number and token value. If
|
| 319 |
+
only two tokens are passed, the resulting output is poor.
|
| 320 |
+
|
| 321 |
+
Round-trip invariant for full input:
|
| 322 |
+
Untokenized source will match input source exactly
|
| 323 |
+
|
| 324 |
+
Round-trip invariant for limited input:
|
| 325 |
+
# Output text will tokenize the back to the input
|
| 326 |
+
t1 = [tok[:2] for tok in generate_tokens(f.readline)]
|
| 327 |
+
newcode = untokenize(t1)
|
| 328 |
+
readline = iter(newcode.splitlines(1)).next
|
| 329 |
+
t2 = [tok[:2] for tokin generate_tokens(readline)]
|
| 330 |
+
assert t1 == t2
|
| 331 |
+
"""
|
| 332 |
+
ut = Untokenizer()
|
| 333 |
+
return ut.untokenize(iterable)
|
| 334 |
+
|
| 335 |
+
def generate_tokens(readline):
|
| 336 |
+
"""
|
| 337 |
+
The generate_tokens() generator requires one argument, readline, which
|
| 338 |
+
must be a callable object which provides the same interface as the
|
| 339 |
+
readline() method of built-in file objects. Each call to the function
|
| 340 |
+
should return one line of input as a string. Alternately, readline
|
| 341 |
+
can be a callable function terminating with StopIteration:
|
| 342 |
+
readline = open(myfile).next # Example of alternate readline
|
| 343 |
+
|
| 344 |
+
The generator produces 5-tuples with these members: the token type; the
|
| 345 |
+
token string; a 2-tuple (srow, scol) of ints specifying the row and
|
| 346 |
+
column where the token begins in the source; a 2-tuple (erow, ecol) of
|
| 347 |
+
ints specifying the row and column where the token ends in the source;
|
| 348 |
+
and the line on which the token was found. The line passed is the
|
| 349 |
+
physical line.
|
| 350 |
+
"""
|
| 351 |
+
lnum = parenlev = continued = 0
|
| 352 |
+
contstr, needcont = '', 0
|
| 353 |
+
contline = None
|
| 354 |
+
indents = [0]
|
| 355 |
+
|
| 356 |
+
# 'stashed' and 'async_*' are used for async/await parsing
|
| 357 |
+
stashed = None
|
| 358 |
+
async_def = False
|
| 359 |
+
async_def_indent = 0
|
| 360 |
+
async_def_nl = False
|
| 361 |
+
|
| 362 |
+
while 1: # loop over lines in stream
|
| 363 |
+
try:
|
| 364 |
+
line = readline()
|
| 365 |
+
except StopIteration:
|
| 366 |
+
line = ''
|
| 367 |
+
lnum = lnum + 1
|
| 368 |
+
pos, max = 0, len(line)
|
| 369 |
+
|
| 370 |
+
if contstr: # continued string
|
| 371 |
+
if not line:
|
| 372 |
+
raise TokenError("EOF in multi-line string", strstart)
|
| 373 |
+
endmatch = endprog.match(line)
|
| 374 |
+
if endmatch:
|
| 375 |
+
pos = end = endmatch.end(0)
|
| 376 |
+
yield (STRING, contstr + line[:end],
|
| 377 |
+
strstart, (lnum, end), contline + line)
|
| 378 |
+
contstr, needcont = '', 0
|
| 379 |
+
contline = None
|
| 380 |
+
elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
|
| 381 |
+
yield (ERRORTOKEN, contstr + line,
|
| 382 |
+
strstart, (lnum, len(line)), contline)
|
| 383 |
+
contstr = ''
|
| 384 |
+
contline = None
|
| 385 |
+
continue
|
| 386 |
+
else:
|
| 387 |
+
contstr = contstr + line
|
| 388 |
+
contline = contline + line
|
| 389 |
+
continue
|
| 390 |
+
|
| 391 |
+
elif parenlev == 0 and not continued: # new statement
|
| 392 |
+
if not line: break
|
| 393 |
+
column = 0
|
| 394 |
+
while pos < max: # measure leading whitespace
|
| 395 |
+
if line[pos] == ' ': column = column + 1
|
| 396 |
+
elif line[pos] == '\t': column = (column//tabsize + 1)*tabsize
|
| 397 |
+
elif line[pos] == '\f': column = 0
|
| 398 |
+
else: break
|
| 399 |
+
pos = pos + 1
|
| 400 |
+
if pos == max: break
|
| 401 |
+
|
| 402 |
+
if stashed:
|
| 403 |
+
yield stashed
|
| 404 |
+
stashed = None
|
| 405 |
+
|
| 406 |
+
if line[pos] in '#\r\n': # skip comments or blank lines
|
| 407 |
+
if line[pos] == '#':
|
| 408 |
+
comment_token = line[pos:].rstrip('\r\n')
|
| 409 |
+
nl_pos = pos + len(comment_token)
|
| 410 |
+
yield (COMMENT, comment_token,
|
| 411 |
+
(lnum, pos), (lnum, pos + len(comment_token)), line)
|
| 412 |
+
yield (NL, line[nl_pos:],
|
| 413 |
+
(lnum, nl_pos), (lnum, len(line)), line)
|
| 414 |
+
else:
|
| 415 |
+
yield ((NL, COMMENT)[line[pos] == '#'], line[pos:],
|
| 416 |
+
(lnum, pos), (lnum, len(line)), line)
|
| 417 |
+
continue
|
| 418 |
+
|
| 419 |
+
if column > indents[-1]: # count indents or dedents
|
| 420 |
+
indents.append(column)
|
| 421 |
+
yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
|
| 422 |
+
while column < indents[-1]:
|
| 423 |
+
if column not in indents:
|
| 424 |
+
raise IndentationError(
|
| 425 |
+
"unindent does not match any outer indentation level",
|
| 426 |
+
("<tokenize>", lnum, pos, line))
|
| 427 |
+
indents = indents[:-1]
|
| 428 |
+
|
| 429 |
+
if async_def and async_def_indent >= indents[-1]:
|
| 430 |
+
async_def = False
|
| 431 |
+
async_def_nl = False
|
| 432 |
+
async_def_indent = 0
|
| 433 |
+
|
| 434 |
+
yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
|
| 435 |
+
|
| 436 |
+
if async_def and async_def_nl and async_def_indent >= indents[-1]:
|
| 437 |
+
async_def = False
|
| 438 |
+
async_def_nl = False
|
| 439 |
+
async_def_indent = 0
|
| 440 |
+
|
| 441 |
+
else: # continued statement
|
| 442 |
+
if not line:
|
| 443 |
+
raise TokenError("EOF in multi-line statement", (lnum, 0))
|
| 444 |
+
continued = 0
|
| 445 |
+
|
| 446 |
+
while pos < max:
|
| 447 |
+
pseudomatch = pseudoprog.match(line, pos)
|
| 448 |
+
if pseudomatch: # scan for tokens
|
| 449 |
+
start, end = pseudomatch.span(1)
|
| 450 |
+
spos, epos, pos = (lnum, start), (lnum, end), end
|
| 451 |
+
token, initial = line[start:end], line[start]
|
| 452 |
+
|
| 453 |
+
if initial in string.digits or \
|
| 454 |
+
(initial == '.' and token != '.'): # ordinary number
|
| 455 |
+
yield (NUMBER, token, spos, epos, line)
|
| 456 |
+
elif initial in '\r\n':
|
| 457 |
+
newline = NEWLINE
|
| 458 |
+
if parenlev > 0:
|
| 459 |
+
newline = NL
|
| 460 |
+
elif async_def:
|
| 461 |
+
async_def_nl = True
|
| 462 |
+
if stashed:
|
| 463 |
+
yield stashed
|
| 464 |
+
stashed = None
|
| 465 |
+
yield (newline, token, spos, epos, line)
|
| 466 |
+
|
| 467 |
+
elif initial == '#':
|
| 468 |
+
assert not token.endswith("\n")
|
| 469 |
+
if stashed:
|
| 470 |
+
yield stashed
|
| 471 |
+
stashed = None
|
| 472 |
+
yield (COMMENT, token, spos, epos, line)
|
| 473 |
+
elif token in triple_quoted:
|
| 474 |
+
endprog = endprogs[token]
|
| 475 |
+
endmatch = endprog.match(line, pos)
|
| 476 |
+
if endmatch: # all on one line
|
| 477 |
+
pos = endmatch.end(0)
|
| 478 |
+
token = line[start:pos]
|
| 479 |
+
if stashed:
|
| 480 |
+
yield stashed
|
| 481 |
+
stashed = None
|
| 482 |
+
yield (STRING, token, spos, (lnum, pos), line)
|
| 483 |
+
else:
|
| 484 |
+
strstart = (lnum, start) # multiple lines
|
| 485 |
+
contstr = line[start:]
|
| 486 |
+
contline = line
|
| 487 |
+
break
|
| 488 |
+
elif initial in single_quoted or \
|
| 489 |
+
token[:2] in single_quoted or \
|
| 490 |
+
token[:3] in single_quoted:
|
| 491 |
+
if token[-1] == '\n': # continued string
|
| 492 |
+
strstart = (lnum, start)
|
| 493 |
+
endprog = (endprogs[initial] or endprogs[token[1]] or
|
| 494 |
+
endprogs[token[2]])
|
| 495 |
+
contstr, needcont = line[start:], 1
|
| 496 |
+
contline = line
|
| 497 |
+
break
|
| 498 |
+
else: # ordinary string
|
| 499 |
+
if stashed:
|
| 500 |
+
yield stashed
|
| 501 |
+
stashed = None
|
| 502 |
+
yield (STRING, token, spos, epos, line)
|
| 503 |
+
elif initial.isidentifier(): # ordinary name
|
| 504 |
+
if token in ('async', 'await'):
|
| 505 |
+
if async_def:
|
| 506 |
+
yield (ASYNC if token == 'async' else AWAIT,
|
| 507 |
+
token, spos, epos, line)
|
| 508 |
+
continue
|
| 509 |
+
|
| 510 |
+
tok = (NAME, token, spos, epos, line)
|
| 511 |
+
if token == 'async' and not stashed:
|
| 512 |
+
stashed = tok
|
| 513 |
+
continue
|
| 514 |
+
|
| 515 |
+
if token in ('def', 'for'):
|
| 516 |
+
if (stashed
|
| 517 |
+
and stashed[0] == NAME
|
| 518 |
+
and stashed[1] == 'async'):
|
| 519 |
+
|
| 520 |
+
if token == 'def':
|
| 521 |
+
async_def = True
|
| 522 |
+
async_def_indent = indents[-1]
|
| 523 |
+
|
| 524 |
+
yield (ASYNC, stashed[1],
|
| 525 |
+
stashed[2], stashed[3],
|
| 526 |
+
stashed[4])
|
| 527 |
+
stashed = None
|
| 528 |
+
|
| 529 |
+
if stashed:
|
| 530 |
+
yield stashed
|
| 531 |
+
stashed = None
|
| 532 |
+
|
| 533 |
+
yield tok
|
| 534 |
+
elif initial == '\\': # continued stmt
|
| 535 |
+
# This yield is new; needed for better idempotency:
|
| 536 |
+
if stashed:
|
| 537 |
+
yield stashed
|
| 538 |
+
stashed = None
|
| 539 |
+
yield (NL, token, spos, (lnum, pos), line)
|
| 540 |
+
continued = 1
|
| 541 |
+
else:
|
| 542 |
+
if initial in '([{': parenlev = parenlev + 1
|
| 543 |
+
elif initial in ')]}': parenlev = parenlev - 1
|
| 544 |
+
if stashed:
|
| 545 |
+
yield stashed
|
| 546 |
+
stashed = None
|
| 547 |
+
yield (OP, token, spos, epos, line)
|
| 548 |
+
else:
|
| 549 |
+
yield (ERRORTOKEN, line[pos],
|
| 550 |
+
(lnum, pos), (lnum, pos+1), line)
|
| 551 |
+
pos = pos + 1
|
| 552 |
+
|
| 553 |
+
if stashed:
|
| 554 |
+
yield stashed
|
| 555 |
+
stashed = None
|
| 556 |
+
|
| 557 |
+
for indent in indents[1:]: # pop remaining indent levels
|
| 558 |
+
yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
|
| 559 |
+
yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
|
| 560 |
+
|
| 561 |
+
if __name__ == '__main__': # testing
|
| 562 |
+
import sys
|
| 563 |
+
if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline)
|
| 564 |
+
else: tokenize(sys.stdin.readline)
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Author: Collin Winter
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from test.support import load_package_tests
|
| 6 |
+
|
| 7 |
+
def load_tests(*args):
|
| 8 |
+
return load_package_tests(os.path.dirname(__file__), *args)
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/__main__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import load_tests
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
unittest.main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/README
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
In this directory:
|
| 2 |
+
- py2_test_grammar.py -- test file that exercises most/all of Python 2.x's grammar.
|
| 3 |
+
- py3_test_grammar.py -- test file that exercises most/all of Python 3.x's grammar.
|
| 4 |
+
- infinite_recursion.py -- test file that causes lib2to3's faster recursive pattern matching
|
| 5 |
+
scheme to fail, but passes when lib2to3 falls back to iterative pattern matching.
|
| 6 |
+
- fixes/ -- for use by test_refactor.py
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/bom.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding: utf-8
|
| 2 |
+
print "BOM BOOM!"
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/crlf.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
print "hi"
|
| 2 |
+
|
| 3 |
+
print "Like bad Windows newlines?"
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/different_encoding.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
print u'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ'
|
| 4 |
+
|
| 5 |
+
def f(x):
|
| 6 |
+
print '%s\t-> α(%2i):%s β(%s)'
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/false_encoding.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
print '#coding=0'
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/bad_order.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib2to3.fixer_base import BaseFix
|
| 2 |
+
|
| 3 |
+
class FixBadOrder(BaseFix):
|
| 4 |
+
|
| 5 |
+
order = "crazy"
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_explicit.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib2to3.fixer_base import BaseFix
|
| 2 |
+
|
| 3 |
+
class FixExplicit(BaseFix):
|
| 4 |
+
explicit = True
|
| 5 |
+
|
| 6 |
+
def match(self): return False
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_first.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib2to3.fixer_base import BaseFix
|
| 2 |
+
|
| 3 |
+
class FixFirst(BaseFix):
|
| 4 |
+
run_order = 1
|
| 5 |
+
|
| 6 |
+
def match(self, node): return False
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_last.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib2to3.fixer_base import BaseFix
|
| 2 |
+
|
| 3 |
+
class FixLast(BaseFix):
|
| 4 |
+
|
| 5 |
+
run_order = 10
|
| 6 |
+
|
| 7 |
+
def match(self, node): return False
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_parrot.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib2to3.fixer_base import BaseFix
|
| 2 |
+
from lib2to3.fixer_util import Name
|
| 3 |
+
|
| 4 |
+
class FixParrot(BaseFix):
|
| 5 |
+
"""
|
| 6 |
+
Change functions named 'parrot' to 'cheese'.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
PATTERN = """funcdef < 'def' name='parrot' any* >"""
|
| 10 |
+
|
| 11 |
+
def transform(self, node, results):
|
| 12 |
+
name = results["name"]
|
| 13 |
+
name.replace(Name("cheese", name.prefix))
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/myfixes/fix_preorder.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from lib2to3.fixer_base import BaseFix
|
| 2 |
+
|
| 3 |
+
class FixPreorder(BaseFix):
|
| 4 |
+
order = "pre"
|
| 5 |
+
|
| 6 |
+
def match(self, node): return False
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/no_fixer_cls.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# This is empty so trying to fetch the fixer class gives an AttributeError
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/fixers/parrot_example.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def parrot():
|
| 2 |
+
pass
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/infinite_recursion.py
ADDED
|
@@ -0,0 +1,2669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Verify that 2to3 falls back from the recursive pattern matching scheme to a
|
| 2 |
+
# slower, iterative scheme in the event of a RecursionError.
|
| 3 |
+
from ctypes import *
|
| 4 |
+
STRING = c_char_p
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
OSUnknownByteOrder = 0
|
| 8 |
+
UIT_PROMPT = 1
|
| 9 |
+
P_PGID = 2
|
| 10 |
+
P_PID = 1
|
| 11 |
+
UIT_ERROR = 5
|
| 12 |
+
UIT_INFO = 4
|
| 13 |
+
UIT_NONE = 0
|
| 14 |
+
P_ALL = 0
|
| 15 |
+
UIT_VERIFY = 2
|
| 16 |
+
OSBigEndian = 2
|
| 17 |
+
UIT_BOOLEAN = 3
|
| 18 |
+
OSLittleEndian = 1
|
| 19 |
+
__darwin_nl_item = c_int
|
| 20 |
+
__darwin_wctrans_t = c_int
|
| 21 |
+
__darwin_wctype_t = c_ulong
|
| 22 |
+
__int8_t = c_byte
|
| 23 |
+
__uint8_t = c_ubyte
|
| 24 |
+
__int16_t = c_short
|
| 25 |
+
__uint16_t = c_ushort
|
| 26 |
+
__int32_t = c_int
|
| 27 |
+
__uint32_t = c_uint
|
| 28 |
+
__int64_t = c_longlong
|
| 29 |
+
__uint64_t = c_ulonglong
|
| 30 |
+
__darwin_intptr_t = c_long
|
| 31 |
+
__darwin_natural_t = c_uint
|
| 32 |
+
__darwin_ct_rune_t = c_int
|
| 33 |
+
class __mbstate_t(Union):
|
| 34 |
+
pass
|
| 35 |
+
__mbstate_t._pack_ = 4
|
| 36 |
+
__mbstate_t._fields_ = [
|
| 37 |
+
('__mbstate8', c_char * 128),
|
| 38 |
+
('_mbstateL', c_longlong),
|
| 39 |
+
]
|
| 40 |
+
assert sizeof(__mbstate_t) == 128, sizeof(__mbstate_t)
|
| 41 |
+
assert alignment(__mbstate_t) == 4, alignment(__mbstate_t)
|
| 42 |
+
__darwin_mbstate_t = __mbstate_t
|
| 43 |
+
__darwin_ptrdiff_t = c_int
|
| 44 |
+
__darwin_size_t = c_ulong
|
| 45 |
+
__darwin_va_list = STRING
|
| 46 |
+
__darwin_wchar_t = c_int
|
| 47 |
+
__darwin_rune_t = __darwin_wchar_t
|
| 48 |
+
__darwin_wint_t = c_int
|
| 49 |
+
__darwin_clock_t = c_ulong
|
| 50 |
+
__darwin_socklen_t = __uint32_t
|
| 51 |
+
__darwin_ssize_t = c_long
|
| 52 |
+
__darwin_time_t = c_long
|
| 53 |
+
sig_atomic_t = c_int
|
| 54 |
+
class sigcontext(Structure):
|
| 55 |
+
pass
|
| 56 |
+
sigcontext._fields_ = [
|
| 57 |
+
('sc_onstack', c_int),
|
| 58 |
+
('sc_mask', c_int),
|
| 59 |
+
('sc_eax', c_uint),
|
| 60 |
+
('sc_ebx', c_uint),
|
| 61 |
+
('sc_ecx', c_uint),
|
| 62 |
+
('sc_edx', c_uint),
|
| 63 |
+
('sc_edi', c_uint),
|
| 64 |
+
('sc_esi', c_uint),
|
| 65 |
+
('sc_ebp', c_uint),
|
| 66 |
+
('sc_esp', c_uint),
|
| 67 |
+
('sc_ss', c_uint),
|
| 68 |
+
('sc_eflags', c_uint),
|
| 69 |
+
('sc_eip', c_uint),
|
| 70 |
+
('sc_cs', c_uint),
|
| 71 |
+
('sc_ds', c_uint),
|
| 72 |
+
('sc_es', c_uint),
|
| 73 |
+
('sc_fs', c_uint),
|
| 74 |
+
('sc_gs', c_uint),
|
| 75 |
+
]
|
| 76 |
+
assert sizeof(sigcontext) == 72, sizeof(sigcontext)
|
| 77 |
+
assert alignment(sigcontext) == 4, alignment(sigcontext)
|
| 78 |
+
u_int8_t = c_ubyte
|
| 79 |
+
u_int16_t = c_ushort
|
| 80 |
+
u_int32_t = c_uint
|
| 81 |
+
u_int64_t = c_ulonglong
|
| 82 |
+
int32_t = c_int
|
| 83 |
+
register_t = int32_t
|
| 84 |
+
user_addr_t = u_int64_t
|
| 85 |
+
user_size_t = u_int64_t
|
| 86 |
+
int64_t = c_longlong
|
| 87 |
+
user_ssize_t = int64_t
|
| 88 |
+
user_long_t = int64_t
|
| 89 |
+
user_ulong_t = u_int64_t
|
| 90 |
+
user_time_t = int64_t
|
| 91 |
+
syscall_arg_t = u_int64_t
|
| 92 |
+
|
| 93 |
+
# values for unnamed enumeration
|
| 94 |
+
class aes_key_st(Structure):
|
| 95 |
+
pass
|
| 96 |
+
aes_key_st._fields_ = [
|
| 97 |
+
('rd_key', c_ulong * 60),
|
| 98 |
+
('rounds', c_int),
|
| 99 |
+
]
|
| 100 |
+
assert sizeof(aes_key_st) == 244, sizeof(aes_key_st)
|
| 101 |
+
assert alignment(aes_key_st) == 4, alignment(aes_key_st)
|
| 102 |
+
AES_KEY = aes_key_st
|
| 103 |
+
class asn1_ctx_st(Structure):
|
| 104 |
+
pass
|
| 105 |
+
asn1_ctx_st._fields_ = [
|
| 106 |
+
('p', POINTER(c_ubyte)),
|
| 107 |
+
('eos', c_int),
|
| 108 |
+
('error', c_int),
|
| 109 |
+
('inf', c_int),
|
| 110 |
+
('tag', c_int),
|
| 111 |
+
('xclass', c_int),
|
| 112 |
+
('slen', c_long),
|
| 113 |
+
('max', POINTER(c_ubyte)),
|
| 114 |
+
('q', POINTER(c_ubyte)),
|
| 115 |
+
('pp', POINTER(POINTER(c_ubyte))),
|
| 116 |
+
('line', c_int),
|
| 117 |
+
]
|
| 118 |
+
assert sizeof(asn1_ctx_st) == 44, sizeof(asn1_ctx_st)
|
| 119 |
+
assert alignment(asn1_ctx_st) == 4, alignment(asn1_ctx_st)
|
| 120 |
+
ASN1_CTX = asn1_ctx_st
|
| 121 |
+
class asn1_object_st(Structure):
|
| 122 |
+
pass
|
| 123 |
+
asn1_object_st._fields_ = [
|
| 124 |
+
('sn', STRING),
|
| 125 |
+
('ln', STRING),
|
| 126 |
+
('nid', c_int),
|
| 127 |
+
('length', c_int),
|
| 128 |
+
('data', POINTER(c_ubyte)),
|
| 129 |
+
('flags', c_int),
|
| 130 |
+
]
|
| 131 |
+
assert sizeof(asn1_object_st) == 24, sizeof(asn1_object_st)
|
| 132 |
+
assert alignment(asn1_object_st) == 4, alignment(asn1_object_st)
|
| 133 |
+
ASN1_OBJECT = asn1_object_st
|
| 134 |
+
class asn1_string_st(Structure):
|
| 135 |
+
pass
|
| 136 |
+
asn1_string_st._fields_ = [
|
| 137 |
+
('length', c_int),
|
| 138 |
+
('type', c_int),
|
| 139 |
+
('data', POINTER(c_ubyte)),
|
| 140 |
+
('flags', c_long),
|
| 141 |
+
]
|
| 142 |
+
assert sizeof(asn1_string_st) == 16, sizeof(asn1_string_st)
|
| 143 |
+
assert alignment(asn1_string_st) == 4, alignment(asn1_string_st)
|
| 144 |
+
ASN1_STRING = asn1_string_st
|
| 145 |
+
class ASN1_ENCODING_st(Structure):
|
| 146 |
+
pass
|
| 147 |
+
ASN1_ENCODING_st._fields_ = [
|
| 148 |
+
('enc', POINTER(c_ubyte)),
|
| 149 |
+
('len', c_long),
|
| 150 |
+
('modified', c_int),
|
| 151 |
+
]
|
| 152 |
+
assert sizeof(ASN1_ENCODING_st) == 12, sizeof(ASN1_ENCODING_st)
|
| 153 |
+
assert alignment(ASN1_ENCODING_st) == 4, alignment(ASN1_ENCODING_st)
|
| 154 |
+
ASN1_ENCODING = ASN1_ENCODING_st
|
| 155 |
+
class asn1_string_table_st(Structure):
|
| 156 |
+
pass
|
| 157 |
+
asn1_string_table_st._fields_ = [
|
| 158 |
+
('nid', c_int),
|
| 159 |
+
('minsize', c_long),
|
| 160 |
+
('maxsize', c_long),
|
| 161 |
+
('mask', c_ulong),
|
| 162 |
+
('flags', c_ulong),
|
| 163 |
+
]
|
| 164 |
+
assert sizeof(asn1_string_table_st) == 20, sizeof(asn1_string_table_st)
|
| 165 |
+
assert alignment(asn1_string_table_st) == 4, alignment(asn1_string_table_st)
|
| 166 |
+
ASN1_STRING_TABLE = asn1_string_table_st
|
| 167 |
+
class ASN1_TEMPLATE_st(Structure):
|
| 168 |
+
pass
|
| 169 |
+
ASN1_TEMPLATE_st._fields_ = [
|
| 170 |
+
]
|
| 171 |
+
ASN1_TEMPLATE = ASN1_TEMPLATE_st
|
| 172 |
+
class ASN1_ITEM_st(Structure):
|
| 173 |
+
pass
|
| 174 |
+
ASN1_ITEM = ASN1_ITEM_st
|
| 175 |
+
ASN1_ITEM_st._fields_ = [
|
| 176 |
+
]
|
| 177 |
+
class ASN1_TLC_st(Structure):
|
| 178 |
+
pass
|
| 179 |
+
ASN1_TLC = ASN1_TLC_st
|
| 180 |
+
ASN1_TLC_st._fields_ = [
|
| 181 |
+
]
|
| 182 |
+
class ASN1_VALUE_st(Structure):
|
| 183 |
+
pass
|
| 184 |
+
ASN1_VALUE_st._fields_ = [
|
| 185 |
+
]
|
| 186 |
+
ASN1_VALUE = ASN1_VALUE_st
|
| 187 |
+
ASN1_ITEM_EXP = ASN1_ITEM
|
| 188 |
+
class asn1_type_st(Structure):
|
| 189 |
+
pass
|
| 190 |
+
class N12asn1_type_st4DOLLAR_11E(Union):
|
| 191 |
+
pass
|
| 192 |
+
ASN1_BOOLEAN = c_int
|
| 193 |
+
ASN1_INTEGER = asn1_string_st
|
| 194 |
+
ASN1_ENUMERATED = asn1_string_st
|
| 195 |
+
ASN1_BIT_STRING = asn1_string_st
|
| 196 |
+
ASN1_OCTET_STRING = asn1_string_st
|
| 197 |
+
ASN1_PRINTABLESTRING = asn1_string_st
|
| 198 |
+
ASN1_T61STRING = asn1_string_st
|
| 199 |
+
ASN1_IA5STRING = asn1_string_st
|
| 200 |
+
ASN1_GENERALSTRING = asn1_string_st
|
| 201 |
+
ASN1_BMPSTRING = asn1_string_st
|
| 202 |
+
ASN1_UNIVERSALSTRING = asn1_string_st
|
| 203 |
+
ASN1_UTCTIME = asn1_string_st
|
| 204 |
+
ASN1_GENERALIZEDTIME = asn1_string_st
|
| 205 |
+
ASN1_VISIBLESTRING = asn1_string_st
|
| 206 |
+
ASN1_UTF8STRING = asn1_string_st
|
| 207 |
+
N12asn1_type_st4DOLLAR_11E._fields_ = [
|
| 208 |
+
('ptr', STRING),
|
| 209 |
+
('boolean', ASN1_BOOLEAN),
|
| 210 |
+
('asn1_string', POINTER(ASN1_STRING)),
|
| 211 |
+
('object', POINTER(ASN1_OBJECT)),
|
| 212 |
+
('integer', POINTER(ASN1_INTEGER)),
|
| 213 |
+
('enumerated', POINTER(ASN1_ENUMERATED)),
|
| 214 |
+
('bit_string', POINTER(ASN1_BIT_STRING)),
|
| 215 |
+
('octet_string', POINTER(ASN1_OCTET_STRING)),
|
| 216 |
+
('printablestring', POINTER(ASN1_PRINTABLESTRING)),
|
| 217 |
+
('t61string', POINTER(ASN1_T61STRING)),
|
| 218 |
+
('ia5string', POINTER(ASN1_IA5STRING)),
|
| 219 |
+
('generalstring', POINTER(ASN1_GENERALSTRING)),
|
| 220 |
+
('bmpstring', POINTER(ASN1_BMPSTRING)),
|
| 221 |
+
('universalstring', POINTER(ASN1_UNIVERSALSTRING)),
|
| 222 |
+
('utctime', POINTER(ASN1_UTCTIME)),
|
| 223 |
+
('generalizedtime', POINTER(ASN1_GENERALIZEDTIME)),
|
| 224 |
+
('visiblestring', POINTER(ASN1_VISIBLESTRING)),
|
| 225 |
+
('utf8string', POINTER(ASN1_UTF8STRING)),
|
| 226 |
+
('set', POINTER(ASN1_STRING)),
|
| 227 |
+
('sequence', POINTER(ASN1_STRING)),
|
| 228 |
+
]
|
| 229 |
+
assert sizeof(N12asn1_type_st4DOLLAR_11E) == 4, sizeof(N12asn1_type_st4DOLLAR_11E)
|
| 230 |
+
assert alignment(N12asn1_type_st4DOLLAR_11E) == 4, alignment(N12asn1_type_st4DOLLAR_11E)
|
| 231 |
+
asn1_type_st._fields_ = [
|
| 232 |
+
('type', c_int),
|
| 233 |
+
('value', N12asn1_type_st4DOLLAR_11E),
|
| 234 |
+
]
|
| 235 |
+
assert sizeof(asn1_type_st) == 8, sizeof(asn1_type_st)
|
| 236 |
+
assert alignment(asn1_type_st) == 4, alignment(asn1_type_st)
|
| 237 |
+
ASN1_TYPE = asn1_type_st
|
| 238 |
+
class asn1_method_st(Structure):
|
| 239 |
+
pass
|
| 240 |
+
asn1_method_st._fields_ = [
|
| 241 |
+
('i2d', CFUNCTYPE(c_int)),
|
| 242 |
+
('d2i', CFUNCTYPE(STRING)),
|
| 243 |
+
('create', CFUNCTYPE(STRING)),
|
| 244 |
+
('destroy', CFUNCTYPE(None)),
|
| 245 |
+
]
|
| 246 |
+
assert sizeof(asn1_method_st) == 16, sizeof(asn1_method_st)
|
| 247 |
+
assert alignment(asn1_method_st) == 4, alignment(asn1_method_st)
|
| 248 |
+
ASN1_METHOD = asn1_method_st
|
| 249 |
+
class asn1_header_st(Structure):
|
| 250 |
+
pass
|
| 251 |
+
asn1_header_st._fields_ = [
|
| 252 |
+
('header', POINTER(ASN1_OCTET_STRING)),
|
| 253 |
+
('data', STRING),
|
| 254 |
+
('meth', POINTER(ASN1_METHOD)),
|
| 255 |
+
]
|
| 256 |
+
assert sizeof(asn1_header_st) == 12, sizeof(asn1_header_st)
|
| 257 |
+
assert alignment(asn1_header_st) == 4, alignment(asn1_header_st)
|
| 258 |
+
ASN1_HEADER = asn1_header_st
|
| 259 |
+
class BIT_STRING_BITNAME_st(Structure):
|
| 260 |
+
pass
|
| 261 |
+
BIT_STRING_BITNAME_st._fields_ = [
|
| 262 |
+
('bitnum', c_int),
|
| 263 |
+
('lname', STRING),
|
| 264 |
+
('sname', STRING),
|
| 265 |
+
]
|
| 266 |
+
assert sizeof(BIT_STRING_BITNAME_st) == 12, sizeof(BIT_STRING_BITNAME_st)
|
| 267 |
+
assert alignment(BIT_STRING_BITNAME_st) == 4, alignment(BIT_STRING_BITNAME_st)
|
| 268 |
+
BIT_STRING_BITNAME = BIT_STRING_BITNAME_st
|
| 269 |
+
class bio_st(Structure):
|
| 270 |
+
pass
|
| 271 |
+
BIO = bio_st
|
| 272 |
+
bio_info_cb = CFUNCTYPE(None, POINTER(bio_st), c_int, STRING, c_int, c_long, c_long)
|
| 273 |
+
class bio_method_st(Structure):
|
| 274 |
+
pass
|
| 275 |
+
bio_method_st._fields_ = [
|
| 276 |
+
('type', c_int),
|
| 277 |
+
('name', STRING),
|
| 278 |
+
('bwrite', CFUNCTYPE(c_int, POINTER(BIO), STRING, c_int)),
|
| 279 |
+
('bread', CFUNCTYPE(c_int, POINTER(BIO), STRING, c_int)),
|
| 280 |
+
('bputs', CFUNCTYPE(c_int, POINTER(BIO), STRING)),
|
| 281 |
+
('bgets', CFUNCTYPE(c_int, POINTER(BIO), STRING, c_int)),
|
| 282 |
+
('ctrl', CFUNCTYPE(c_long, POINTER(BIO), c_int, c_long, c_void_p)),
|
| 283 |
+
('create', CFUNCTYPE(c_int, POINTER(BIO))),
|
| 284 |
+
('destroy', CFUNCTYPE(c_int, POINTER(BIO))),
|
| 285 |
+
('callback_ctrl', CFUNCTYPE(c_long, POINTER(BIO), c_int, POINTER(bio_info_cb))),
|
| 286 |
+
]
|
| 287 |
+
assert sizeof(bio_method_st) == 40, sizeof(bio_method_st)
|
| 288 |
+
assert alignment(bio_method_st) == 4, alignment(bio_method_st)
|
| 289 |
+
BIO_METHOD = bio_method_st
|
| 290 |
+
class crypto_ex_data_st(Structure):
|
| 291 |
+
pass
|
| 292 |
+
class stack_st(Structure):
|
| 293 |
+
pass
|
| 294 |
+
STACK = stack_st
|
| 295 |
+
crypto_ex_data_st._fields_ = [
|
| 296 |
+
('sk', POINTER(STACK)),
|
| 297 |
+
('dummy', c_int),
|
| 298 |
+
]
|
| 299 |
+
assert sizeof(crypto_ex_data_st) == 8, sizeof(crypto_ex_data_st)
|
| 300 |
+
assert alignment(crypto_ex_data_st) == 4, alignment(crypto_ex_data_st)
|
| 301 |
+
CRYPTO_EX_DATA = crypto_ex_data_st
|
| 302 |
+
bio_st._fields_ = [
|
| 303 |
+
('method', POINTER(BIO_METHOD)),
|
| 304 |
+
('callback', CFUNCTYPE(c_long, POINTER(bio_st), c_int, STRING, c_int, c_long, c_long)),
|
| 305 |
+
('cb_arg', STRING),
|
| 306 |
+
('init', c_int),
|
| 307 |
+
('shutdown', c_int),
|
| 308 |
+
('flags', c_int),
|
| 309 |
+
('retry_reason', c_int),
|
| 310 |
+
('num', c_int),
|
| 311 |
+
('ptr', c_void_p),
|
| 312 |
+
('next_bio', POINTER(bio_st)),
|
| 313 |
+
('prev_bio', POINTER(bio_st)),
|
| 314 |
+
('references', c_int),
|
| 315 |
+
('num_read', c_ulong),
|
| 316 |
+
('num_write', c_ulong),
|
| 317 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 318 |
+
]
|
| 319 |
+
assert sizeof(bio_st) == 64, sizeof(bio_st)
|
| 320 |
+
assert alignment(bio_st) == 4, alignment(bio_st)
|
| 321 |
+
class bio_f_buffer_ctx_struct(Structure):
|
| 322 |
+
pass
|
| 323 |
+
bio_f_buffer_ctx_struct._fields_ = [
|
| 324 |
+
('ibuf_size', c_int),
|
| 325 |
+
('obuf_size', c_int),
|
| 326 |
+
('ibuf', STRING),
|
| 327 |
+
('ibuf_len', c_int),
|
| 328 |
+
('ibuf_off', c_int),
|
| 329 |
+
('obuf', STRING),
|
| 330 |
+
('obuf_len', c_int),
|
| 331 |
+
('obuf_off', c_int),
|
| 332 |
+
]
|
| 333 |
+
assert sizeof(bio_f_buffer_ctx_struct) == 32, sizeof(bio_f_buffer_ctx_struct)
|
| 334 |
+
assert alignment(bio_f_buffer_ctx_struct) == 4, alignment(bio_f_buffer_ctx_struct)
|
| 335 |
+
BIO_F_BUFFER_CTX = bio_f_buffer_ctx_struct
|
| 336 |
+
class hostent(Structure):
|
| 337 |
+
pass
|
| 338 |
+
hostent._fields_ = [
|
| 339 |
+
]
|
| 340 |
+
class bf_key_st(Structure):
|
| 341 |
+
pass
|
| 342 |
+
bf_key_st._fields_ = [
|
| 343 |
+
('P', c_uint * 18),
|
| 344 |
+
('S', c_uint * 1024),
|
| 345 |
+
]
|
| 346 |
+
assert sizeof(bf_key_st) == 4168, sizeof(bf_key_st)
|
| 347 |
+
assert alignment(bf_key_st) == 4, alignment(bf_key_st)
|
| 348 |
+
BF_KEY = bf_key_st
|
| 349 |
+
class bignum_st(Structure):
|
| 350 |
+
pass
|
| 351 |
+
bignum_st._fields_ = [
|
| 352 |
+
('d', POINTER(c_ulong)),
|
| 353 |
+
('top', c_int),
|
| 354 |
+
('dmax', c_int),
|
| 355 |
+
('neg', c_int),
|
| 356 |
+
('flags', c_int),
|
| 357 |
+
]
|
| 358 |
+
assert sizeof(bignum_st) == 20, sizeof(bignum_st)
|
| 359 |
+
assert alignment(bignum_st) == 4, alignment(bignum_st)
|
| 360 |
+
BIGNUM = bignum_st
|
| 361 |
+
class bignum_ctx(Structure):
|
| 362 |
+
pass
|
| 363 |
+
bignum_ctx._fields_ = [
|
| 364 |
+
]
|
| 365 |
+
BN_CTX = bignum_ctx
|
| 366 |
+
class bn_blinding_st(Structure):
|
| 367 |
+
pass
|
| 368 |
+
bn_blinding_st._fields_ = [
|
| 369 |
+
('init', c_int),
|
| 370 |
+
('A', POINTER(BIGNUM)),
|
| 371 |
+
('Ai', POINTER(BIGNUM)),
|
| 372 |
+
('mod', POINTER(BIGNUM)),
|
| 373 |
+
('thread_id', c_ulong),
|
| 374 |
+
]
|
| 375 |
+
assert sizeof(bn_blinding_st) == 20, sizeof(bn_blinding_st)
|
| 376 |
+
assert alignment(bn_blinding_st) == 4, alignment(bn_blinding_st)
|
| 377 |
+
BN_BLINDING = bn_blinding_st
|
| 378 |
+
class bn_mont_ctx_st(Structure):
|
| 379 |
+
pass
|
| 380 |
+
bn_mont_ctx_st._fields_ = [
|
| 381 |
+
('ri', c_int),
|
| 382 |
+
('RR', BIGNUM),
|
| 383 |
+
('N', BIGNUM),
|
| 384 |
+
('Ni', BIGNUM),
|
| 385 |
+
('n0', c_ulong),
|
| 386 |
+
('flags', c_int),
|
| 387 |
+
]
|
| 388 |
+
assert sizeof(bn_mont_ctx_st) == 72, sizeof(bn_mont_ctx_st)
|
| 389 |
+
assert alignment(bn_mont_ctx_st) == 4, alignment(bn_mont_ctx_st)
|
| 390 |
+
BN_MONT_CTX = bn_mont_ctx_st
|
| 391 |
+
class bn_recp_ctx_st(Structure):
|
| 392 |
+
pass
|
| 393 |
+
bn_recp_ctx_st._fields_ = [
|
| 394 |
+
('N', BIGNUM),
|
| 395 |
+
('Nr', BIGNUM),
|
| 396 |
+
('num_bits', c_int),
|
| 397 |
+
('shift', c_int),
|
| 398 |
+
('flags', c_int),
|
| 399 |
+
]
|
| 400 |
+
assert sizeof(bn_recp_ctx_st) == 52, sizeof(bn_recp_ctx_st)
|
| 401 |
+
assert alignment(bn_recp_ctx_st) == 4, alignment(bn_recp_ctx_st)
|
| 402 |
+
BN_RECP_CTX = bn_recp_ctx_st
|
| 403 |
+
class buf_mem_st(Structure):
|
| 404 |
+
pass
|
| 405 |
+
buf_mem_st._fields_ = [
|
| 406 |
+
('length', c_int),
|
| 407 |
+
('data', STRING),
|
| 408 |
+
('max', c_int),
|
| 409 |
+
]
|
| 410 |
+
assert sizeof(buf_mem_st) == 12, sizeof(buf_mem_st)
|
| 411 |
+
assert alignment(buf_mem_st) == 4, alignment(buf_mem_st)
|
| 412 |
+
BUF_MEM = buf_mem_st
|
| 413 |
+
class cast_key_st(Structure):
|
| 414 |
+
pass
|
| 415 |
+
cast_key_st._fields_ = [
|
| 416 |
+
('data', c_ulong * 32),
|
| 417 |
+
('short_key', c_int),
|
| 418 |
+
]
|
| 419 |
+
assert sizeof(cast_key_st) == 132, sizeof(cast_key_st)
|
| 420 |
+
assert alignment(cast_key_st) == 4, alignment(cast_key_st)
|
| 421 |
+
CAST_KEY = cast_key_st
|
| 422 |
+
class comp_method_st(Structure):
|
| 423 |
+
pass
|
| 424 |
+
comp_method_st._fields_ = [
|
| 425 |
+
('type', c_int),
|
| 426 |
+
('name', STRING),
|
| 427 |
+
('init', CFUNCTYPE(c_int)),
|
| 428 |
+
('finish', CFUNCTYPE(None)),
|
| 429 |
+
('compress', CFUNCTYPE(c_int)),
|
| 430 |
+
('expand', CFUNCTYPE(c_int)),
|
| 431 |
+
('ctrl', CFUNCTYPE(c_long)),
|
| 432 |
+
('callback_ctrl', CFUNCTYPE(c_long)),
|
| 433 |
+
]
|
| 434 |
+
assert sizeof(comp_method_st) == 32, sizeof(comp_method_st)
|
| 435 |
+
assert alignment(comp_method_st) == 4, alignment(comp_method_st)
|
| 436 |
+
COMP_METHOD = comp_method_st
|
| 437 |
+
class comp_ctx_st(Structure):
|
| 438 |
+
pass
|
| 439 |
+
comp_ctx_st._fields_ = [
|
| 440 |
+
('meth', POINTER(COMP_METHOD)),
|
| 441 |
+
('compress_in', c_ulong),
|
| 442 |
+
('compress_out', c_ulong),
|
| 443 |
+
('expand_in', c_ulong),
|
| 444 |
+
('expand_out', c_ulong),
|
| 445 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 446 |
+
]
|
| 447 |
+
assert sizeof(comp_ctx_st) == 28, sizeof(comp_ctx_st)
|
| 448 |
+
assert alignment(comp_ctx_st) == 4, alignment(comp_ctx_st)
|
| 449 |
+
COMP_CTX = comp_ctx_st
|
| 450 |
+
class CRYPTO_dynlock_value(Structure):
|
| 451 |
+
pass
|
| 452 |
+
CRYPTO_dynlock_value._fields_ = [
|
| 453 |
+
]
|
| 454 |
+
class CRYPTO_dynlock(Structure):
|
| 455 |
+
pass
|
| 456 |
+
CRYPTO_dynlock._fields_ = [
|
| 457 |
+
('references', c_int),
|
| 458 |
+
('data', POINTER(CRYPTO_dynlock_value)),
|
| 459 |
+
]
|
| 460 |
+
assert sizeof(CRYPTO_dynlock) == 8, sizeof(CRYPTO_dynlock)
|
| 461 |
+
assert alignment(CRYPTO_dynlock) == 4, alignment(CRYPTO_dynlock)
|
| 462 |
+
BIO_dummy = bio_st
|
| 463 |
+
CRYPTO_EX_new = CFUNCTYPE(c_int, c_void_p, c_void_p, POINTER(CRYPTO_EX_DATA), c_int, c_long, c_void_p)
|
| 464 |
+
CRYPTO_EX_free = CFUNCTYPE(None, c_void_p, c_void_p, POINTER(CRYPTO_EX_DATA), c_int, c_long, c_void_p)
|
| 465 |
+
CRYPTO_EX_dup = CFUNCTYPE(c_int, POINTER(CRYPTO_EX_DATA), POINTER(CRYPTO_EX_DATA), c_void_p, c_int, c_long, c_void_p)
|
| 466 |
+
class crypto_ex_data_func_st(Structure):
|
| 467 |
+
pass
|
| 468 |
+
crypto_ex_data_func_st._fields_ = [
|
| 469 |
+
('argl', c_long),
|
| 470 |
+
('argp', c_void_p),
|
| 471 |
+
('new_func', POINTER(CRYPTO_EX_new)),
|
| 472 |
+
('free_func', POINTER(CRYPTO_EX_free)),
|
| 473 |
+
('dup_func', POINTER(CRYPTO_EX_dup)),
|
| 474 |
+
]
|
| 475 |
+
assert sizeof(crypto_ex_data_func_st) == 20, sizeof(crypto_ex_data_func_st)
|
| 476 |
+
assert alignment(crypto_ex_data_func_st) == 4, alignment(crypto_ex_data_func_st)
|
| 477 |
+
CRYPTO_EX_DATA_FUNCS = crypto_ex_data_func_st
|
| 478 |
+
class st_CRYPTO_EX_DATA_IMPL(Structure):
|
| 479 |
+
pass
|
| 480 |
+
CRYPTO_EX_DATA_IMPL = st_CRYPTO_EX_DATA_IMPL
|
| 481 |
+
st_CRYPTO_EX_DATA_IMPL._fields_ = [
|
| 482 |
+
]
|
| 483 |
+
CRYPTO_MEM_LEAK_CB = CFUNCTYPE(c_void_p, c_ulong, STRING, c_int, c_int, c_void_p)
|
| 484 |
+
DES_cblock = c_ubyte * 8
|
| 485 |
+
const_DES_cblock = c_ubyte * 8
|
| 486 |
+
class DES_ks(Structure):
|
| 487 |
+
pass
|
| 488 |
+
class N6DES_ks3DOLLAR_9E(Union):
|
| 489 |
+
pass
|
| 490 |
+
N6DES_ks3DOLLAR_9E._fields_ = [
|
| 491 |
+
('cblock', DES_cblock),
|
| 492 |
+
('deslong', c_ulong * 2),
|
| 493 |
+
]
|
| 494 |
+
assert sizeof(N6DES_ks3DOLLAR_9E) == 8, sizeof(N6DES_ks3DOLLAR_9E)
|
| 495 |
+
assert alignment(N6DES_ks3DOLLAR_9E) == 4, alignment(N6DES_ks3DOLLAR_9E)
|
| 496 |
+
DES_ks._fields_ = [
|
| 497 |
+
('ks', N6DES_ks3DOLLAR_9E * 16),
|
| 498 |
+
]
|
| 499 |
+
assert sizeof(DES_ks) == 128, sizeof(DES_ks)
|
| 500 |
+
assert alignment(DES_ks) == 4, alignment(DES_ks)
|
| 501 |
+
DES_key_schedule = DES_ks
|
| 502 |
+
_ossl_old_des_cblock = c_ubyte * 8
|
| 503 |
+
class _ossl_old_des_ks_struct(Structure):
|
| 504 |
+
pass
|
| 505 |
+
class N23_ossl_old_des_ks_struct4DOLLAR_10E(Union):
|
| 506 |
+
pass
|
| 507 |
+
N23_ossl_old_des_ks_struct4DOLLAR_10E._fields_ = [
|
| 508 |
+
('_', _ossl_old_des_cblock),
|
| 509 |
+
('pad', c_ulong * 2),
|
| 510 |
+
]
|
| 511 |
+
assert sizeof(N23_ossl_old_des_ks_struct4DOLLAR_10E) == 8, sizeof(N23_ossl_old_des_ks_struct4DOLLAR_10E)
|
| 512 |
+
assert alignment(N23_ossl_old_des_ks_struct4DOLLAR_10E) == 4, alignment(N23_ossl_old_des_ks_struct4DOLLAR_10E)
|
| 513 |
+
_ossl_old_des_ks_struct._fields_ = [
|
| 514 |
+
('ks', N23_ossl_old_des_ks_struct4DOLLAR_10E),
|
| 515 |
+
]
|
| 516 |
+
assert sizeof(_ossl_old_des_ks_struct) == 8, sizeof(_ossl_old_des_ks_struct)
|
| 517 |
+
assert alignment(_ossl_old_des_ks_struct) == 4, alignment(_ossl_old_des_ks_struct)
|
| 518 |
+
_ossl_old_des_key_schedule = _ossl_old_des_ks_struct * 16
|
| 519 |
+
class dh_st(Structure):
|
| 520 |
+
pass
|
| 521 |
+
DH = dh_st
|
| 522 |
+
class dh_method(Structure):
|
| 523 |
+
pass
|
| 524 |
+
dh_method._fields_ = [
|
| 525 |
+
('name', STRING),
|
| 526 |
+
('generate_key', CFUNCTYPE(c_int, POINTER(DH))),
|
| 527 |
+
('compute_key', CFUNCTYPE(c_int, POINTER(c_ubyte), POINTER(BIGNUM), POINTER(DH))),
|
| 528 |
+
('bn_mod_exp', CFUNCTYPE(c_int, POINTER(DH), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BN_CTX), POINTER(BN_MONT_CTX))),
|
| 529 |
+
('init', CFUNCTYPE(c_int, POINTER(DH))),
|
| 530 |
+
('finish', CFUNCTYPE(c_int, POINTER(DH))),
|
| 531 |
+
('flags', c_int),
|
| 532 |
+
('app_data', STRING),
|
| 533 |
+
]
|
| 534 |
+
assert sizeof(dh_method) == 32, sizeof(dh_method)
|
| 535 |
+
assert alignment(dh_method) == 4, alignment(dh_method)
|
| 536 |
+
DH_METHOD = dh_method
|
| 537 |
+
class engine_st(Structure):
|
| 538 |
+
pass
|
| 539 |
+
ENGINE = engine_st
|
| 540 |
+
dh_st._fields_ = [
|
| 541 |
+
('pad', c_int),
|
| 542 |
+
('version', c_int),
|
| 543 |
+
('p', POINTER(BIGNUM)),
|
| 544 |
+
('g', POINTER(BIGNUM)),
|
| 545 |
+
('length', c_long),
|
| 546 |
+
('pub_key', POINTER(BIGNUM)),
|
| 547 |
+
('priv_key', POINTER(BIGNUM)),
|
| 548 |
+
('flags', c_int),
|
| 549 |
+
('method_mont_p', STRING),
|
| 550 |
+
('q', POINTER(BIGNUM)),
|
| 551 |
+
('j', POINTER(BIGNUM)),
|
| 552 |
+
('seed', POINTER(c_ubyte)),
|
| 553 |
+
('seedlen', c_int),
|
| 554 |
+
('counter', POINTER(BIGNUM)),
|
| 555 |
+
('references', c_int),
|
| 556 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 557 |
+
('meth', POINTER(DH_METHOD)),
|
| 558 |
+
('engine', POINTER(ENGINE)),
|
| 559 |
+
]
|
| 560 |
+
assert sizeof(dh_st) == 76, sizeof(dh_st)
|
| 561 |
+
assert alignment(dh_st) == 4, alignment(dh_st)
|
| 562 |
+
class dsa_st(Structure):
|
| 563 |
+
pass
|
| 564 |
+
DSA = dsa_st
|
| 565 |
+
class DSA_SIG_st(Structure):
|
| 566 |
+
pass
|
| 567 |
+
DSA_SIG_st._fields_ = [
|
| 568 |
+
('r', POINTER(BIGNUM)),
|
| 569 |
+
('s', POINTER(BIGNUM)),
|
| 570 |
+
]
|
| 571 |
+
assert sizeof(DSA_SIG_st) == 8, sizeof(DSA_SIG_st)
|
| 572 |
+
assert alignment(DSA_SIG_st) == 4, alignment(DSA_SIG_st)
|
| 573 |
+
DSA_SIG = DSA_SIG_st
|
| 574 |
+
class dsa_method(Structure):
|
| 575 |
+
pass
|
| 576 |
+
dsa_method._fields_ = [
|
| 577 |
+
('name', STRING),
|
| 578 |
+
('dsa_do_sign', CFUNCTYPE(POINTER(DSA_SIG), POINTER(c_ubyte), c_int, POINTER(DSA))),
|
| 579 |
+
('dsa_sign_setup', CFUNCTYPE(c_int, POINTER(DSA), POINTER(BN_CTX), POINTER(POINTER(BIGNUM)), POINTER(POINTER(BIGNUM)))),
|
| 580 |
+
('dsa_do_verify', CFUNCTYPE(c_int, POINTER(c_ubyte), c_int, POINTER(DSA_SIG), POINTER(DSA))),
|
| 581 |
+
('dsa_mod_exp', CFUNCTYPE(c_int, POINTER(DSA), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BN_CTX), POINTER(BN_MONT_CTX))),
|
| 582 |
+
('bn_mod_exp', CFUNCTYPE(c_int, POINTER(DSA), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BN_CTX), POINTER(BN_MONT_CTX))),
|
| 583 |
+
('init', CFUNCTYPE(c_int, POINTER(DSA))),
|
| 584 |
+
('finish', CFUNCTYPE(c_int, POINTER(DSA))),
|
| 585 |
+
('flags', c_int),
|
| 586 |
+
('app_data', STRING),
|
| 587 |
+
]
|
| 588 |
+
assert sizeof(dsa_method) == 40, sizeof(dsa_method)
|
| 589 |
+
assert alignment(dsa_method) == 4, alignment(dsa_method)
|
| 590 |
+
DSA_METHOD = dsa_method
|
| 591 |
+
dsa_st._fields_ = [
|
| 592 |
+
('pad', c_int),
|
| 593 |
+
('version', c_long),
|
| 594 |
+
('write_params', c_int),
|
| 595 |
+
('p', POINTER(BIGNUM)),
|
| 596 |
+
('q', POINTER(BIGNUM)),
|
| 597 |
+
('g', POINTER(BIGNUM)),
|
| 598 |
+
('pub_key', POINTER(BIGNUM)),
|
| 599 |
+
('priv_key', POINTER(BIGNUM)),
|
| 600 |
+
('kinv', POINTER(BIGNUM)),
|
| 601 |
+
('r', POINTER(BIGNUM)),
|
| 602 |
+
('flags', c_int),
|
| 603 |
+
('method_mont_p', STRING),
|
| 604 |
+
('references', c_int),
|
| 605 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 606 |
+
('meth', POINTER(DSA_METHOD)),
|
| 607 |
+
('engine', POINTER(ENGINE)),
|
| 608 |
+
]
|
| 609 |
+
assert sizeof(dsa_st) == 68, sizeof(dsa_st)
|
| 610 |
+
assert alignment(dsa_st) == 4, alignment(dsa_st)
|
| 611 |
+
class evp_pkey_st(Structure):
|
| 612 |
+
pass
|
| 613 |
+
class N11evp_pkey_st4DOLLAR_12E(Union):
|
| 614 |
+
pass
|
| 615 |
+
class rsa_st(Structure):
|
| 616 |
+
pass
|
| 617 |
+
N11evp_pkey_st4DOLLAR_12E._fields_ = [
|
| 618 |
+
('ptr', STRING),
|
| 619 |
+
('rsa', POINTER(rsa_st)),
|
| 620 |
+
('dsa', POINTER(dsa_st)),
|
| 621 |
+
('dh', POINTER(dh_st)),
|
| 622 |
+
]
|
| 623 |
+
assert sizeof(N11evp_pkey_st4DOLLAR_12E) == 4, sizeof(N11evp_pkey_st4DOLLAR_12E)
|
| 624 |
+
assert alignment(N11evp_pkey_st4DOLLAR_12E) == 4, alignment(N11evp_pkey_st4DOLLAR_12E)
|
| 625 |
+
evp_pkey_st._fields_ = [
|
| 626 |
+
('type', c_int),
|
| 627 |
+
('save_type', c_int),
|
| 628 |
+
('references', c_int),
|
| 629 |
+
('pkey', N11evp_pkey_st4DOLLAR_12E),
|
| 630 |
+
('save_parameters', c_int),
|
| 631 |
+
('attributes', POINTER(STACK)),
|
| 632 |
+
]
|
| 633 |
+
assert sizeof(evp_pkey_st) == 24, sizeof(evp_pkey_st)
|
| 634 |
+
assert alignment(evp_pkey_st) == 4, alignment(evp_pkey_st)
|
| 635 |
+
class env_md_st(Structure):
|
| 636 |
+
pass
|
| 637 |
+
class env_md_ctx_st(Structure):
|
| 638 |
+
pass
|
| 639 |
+
EVP_MD_CTX = env_md_ctx_st
|
| 640 |
+
env_md_st._fields_ = [
|
| 641 |
+
('type', c_int),
|
| 642 |
+
('pkey_type', c_int),
|
| 643 |
+
('md_size', c_int),
|
| 644 |
+
('flags', c_ulong),
|
| 645 |
+
('init', CFUNCTYPE(c_int, POINTER(EVP_MD_CTX))),
|
| 646 |
+
('update', CFUNCTYPE(c_int, POINTER(EVP_MD_CTX), c_void_p, c_ulong)),
|
| 647 |
+
('final', CFUNCTYPE(c_int, POINTER(EVP_MD_CTX), POINTER(c_ubyte))),
|
| 648 |
+
('copy', CFUNCTYPE(c_int, POINTER(EVP_MD_CTX), POINTER(EVP_MD_CTX))),
|
| 649 |
+
('cleanup', CFUNCTYPE(c_int, POINTER(EVP_MD_CTX))),
|
| 650 |
+
('sign', CFUNCTYPE(c_int)),
|
| 651 |
+
('verify', CFUNCTYPE(c_int)),
|
| 652 |
+
('required_pkey_type', c_int * 5),
|
| 653 |
+
('block_size', c_int),
|
| 654 |
+
('ctx_size', c_int),
|
| 655 |
+
]
|
| 656 |
+
assert sizeof(env_md_st) == 72, sizeof(env_md_st)
|
| 657 |
+
assert alignment(env_md_st) == 4, alignment(env_md_st)
|
| 658 |
+
EVP_MD = env_md_st
|
| 659 |
+
env_md_ctx_st._fields_ = [
|
| 660 |
+
('digest', POINTER(EVP_MD)),
|
| 661 |
+
('engine', POINTER(ENGINE)),
|
| 662 |
+
('flags', c_ulong),
|
| 663 |
+
('md_data', c_void_p),
|
| 664 |
+
]
|
| 665 |
+
assert sizeof(env_md_ctx_st) == 16, sizeof(env_md_ctx_st)
|
| 666 |
+
assert alignment(env_md_ctx_st) == 4, alignment(env_md_ctx_st)
|
| 667 |
+
class evp_cipher_st(Structure):
|
| 668 |
+
pass
|
| 669 |
+
class evp_cipher_ctx_st(Structure):
|
| 670 |
+
pass
|
| 671 |
+
EVP_CIPHER_CTX = evp_cipher_ctx_st
|
| 672 |
+
evp_cipher_st._fields_ = [
|
| 673 |
+
('nid', c_int),
|
| 674 |
+
('block_size', c_int),
|
| 675 |
+
('key_len', c_int),
|
| 676 |
+
('iv_len', c_int),
|
| 677 |
+
('flags', c_ulong),
|
| 678 |
+
('init', CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX), POINTER(c_ubyte), POINTER(c_ubyte), c_int)),
|
| 679 |
+
('do_cipher', CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX), POINTER(c_ubyte), POINTER(c_ubyte), c_uint)),
|
| 680 |
+
('cleanup', CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX))),
|
| 681 |
+
('ctx_size', c_int),
|
| 682 |
+
('set_asn1_parameters', CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX), POINTER(ASN1_TYPE))),
|
| 683 |
+
('get_asn1_parameters', CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX), POINTER(ASN1_TYPE))),
|
| 684 |
+
('ctrl', CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX), c_int, c_int, c_void_p)),
|
| 685 |
+
('app_data', c_void_p),
|
| 686 |
+
]
|
| 687 |
+
assert sizeof(evp_cipher_st) == 52, sizeof(evp_cipher_st)
|
| 688 |
+
assert alignment(evp_cipher_st) == 4, alignment(evp_cipher_st)
|
| 689 |
+
class evp_cipher_info_st(Structure):
|
| 690 |
+
pass
|
| 691 |
+
EVP_CIPHER = evp_cipher_st
|
| 692 |
+
evp_cipher_info_st._fields_ = [
|
| 693 |
+
('cipher', POINTER(EVP_CIPHER)),
|
| 694 |
+
('iv', c_ubyte * 16),
|
| 695 |
+
]
|
| 696 |
+
assert sizeof(evp_cipher_info_st) == 20, sizeof(evp_cipher_info_st)
|
| 697 |
+
assert alignment(evp_cipher_info_st) == 4, alignment(evp_cipher_info_st)
|
| 698 |
+
EVP_CIPHER_INFO = evp_cipher_info_st
|
| 699 |
+
evp_cipher_ctx_st._fields_ = [
|
| 700 |
+
('cipher', POINTER(EVP_CIPHER)),
|
| 701 |
+
('engine', POINTER(ENGINE)),
|
| 702 |
+
('encrypt', c_int),
|
| 703 |
+
('buf_len', c_int),
|
| 704 |
+
('oiv', c_ubyte * 16),
|
| 705 |
+
('iv', c_ubyte * 16),
|
| 706 |
+
('buf', c_ubyte * 32),
|
| 707 |
+
('num', c_int),
|
| 708 |
+
('app_data', c_void_p),
|
| 709 |
+
('key_len', c_int),
|
| 710 |
+
('flags', c_ulong),
|
| 711 |
+
('cipher_data', c_void_p),
|
| 712 |
+
('final_used', c_int),
|
| 713 |
+
('block_mask', c_int),
|
| 714 |
+
('final', c_ubyte * 32),
|
| 715 |
+
]
|
| 716 |
+
assert sizeof(evp_cipher_ctx_st) == 140, sizeof(evp_cipher_ctx_st)
|
| 717 |
+
assert alignment(evp_cipher_ctx_st) == 4, alignment(evp_cipher_ctx_st)
|
| 718 |
+
class evp_Encode_Ctx_st(Structure):
|
| 719 |
+
pass
|
| 720 |
+
evp_Encode_Ctx_st._fields_ = [
|
| 721 |
+
('num', c_int),
|
| 722 |
+
('length', c_int),
|
| 723 |
+
('enc_data', c_ubyte * 80),
|
| 724 |
+
('line_num', c_int),
|
| 725 |
+
('expect_nl', c_int),
|
| 726 |
+
]
|
| 727 |
+
assert sizeof(evp_Encode_Ctx_st) == 96, sizeof(evp_Encode_Ctx_st)
|
| 728 |
+
assert alignment(evp_Encode_Ctx_st) == 4, alignment(evp_Encode_Ctx_st)
|
| 729 |
+
EVP_ENCODE_CTX = evp_Encode_Ctx_st
|
| 730 |
+
EVP_PBE_KEYGEN = CFUNCTYPE(c_int, POINTER(EVP_CIPHER_CTX), STRING, c_int, POINTER(ASN1_TYPE), POINTER(EVP_CIPHER), POINTER(EVP_MD), c_int)
|
| 731 |
+
class lhash_node_st(Structure):
|
| 732 |
+
pass
|
| 733 |
+
lhash_node_st._fields_ = [
|
| 734 |
+
('data', c_void_p),
|
| 735 |
+
('next', POINTER(lhash_node_st)),
|
| 736 |
+
('hash', c_ulong),
|
| 737 |
+
]
|
| 738 |
+
assert sizeof(lhash_node_st) == 12, sizeof(lhash_node_st)
|
| 739 |
+
assert alignment(lhash_node_st) == 4, alignment(lhash_node_st)
|
| 740 |
+
LHASH_NODE = lhash_node_st
|
| 741 |
+
LHASH_COMP_FN_TYPE = CFUNCTYPE(c_int, c_void_p, c_void_p)
|
| 742 |
+
LHASH_HASH_FN_TYPE = CFUNCTYPE(c_ulong, c_void_p)
|
| 743 |
+
LHASH_DOALL_FN_TYPE = CFUNCTYPE(None, c_void_p)
|
| 744 |
+
LHASH_DOALL_ARG_FN_TYPE = CFUNCTYPE(None, c_void_p, c_void_p)
|
| 745 |
+
class lhash_st(Structure):
|
| 746 |
+
pass
|
| 747 |
+
lhash_st._fields_ = [
|
| 748 |
+
('b', POINTER(POINTER(LHASH_NODE))),
|
| 749 |
+
('comp', LHASH_COMP_FN_TYPE),
|
| 750 |
+
('hash', LHASH_HASH_FN_TYPE),
|
| 751 |
+
('num_nodes', c_uint),
|
| 752 |
+
('num_alloc_nodes', c_uint),
|
| 753 |
+
('p', c_uint),
|
| 754 |
+
('pmax', c_uint),
|
| 755 |
+
('up_load', c_ulong),
|
| 756 |
+
('down_load', c_ulong),
|
| 757 |
+
('num_items', c_ulong),
|
| 758 |
+
('num_expands', c_ulong),
|
| 759 |
+
('num_expand_reallocs', c_ulong),
|
| 760 |
+
('num_contracts', c_ulong),
|
| 761 |
+
('num_contract_reallocs', c_ulong),
|
| 762 |
+
('num_hash_calls', c_ulong),
|
| 763 |
+
('num_comp_calls', c_ulong),
|
| 764 |
+
('num_insert', c_ulong),
|
| 765 |
+
('num_replace', c_ulong),
|
| 766 |
+
('num_delete', c_ulong),
|
| 767 |
+
('num_no_delete', c_ulong),
|
| 768 |
+
('num_retrieve', c_ulong),
|
| 769 |
+
('num_retrieve_miss', c_ulong),
|
| 770 |
+
('num_hash_comps', c_ulong),
|
| 771 |
+
('error', c_int),
|
| 772 |
+
]
|
| 773 |
+
assert sizeof(lhash_st) == 96, sizeof(lhash_st)
|
| 774 |
+
assert alignment(lhash_st) == 4, alignment(lhash_st)
|
| 775 |
+
LHASH = lhash_st
|
| 776 |
+
class MD2state_st(Structure):
|
| 777 |
+
pass
|
| 778 |
+
MD2state_st._fields_ = [
|
| 779 |
+
('num', c_int),
|
| 780 |
+
('data', c_ubyte * 16),
|
| 781 |
+
('cksm', c_uint * 16),
|
| 782 |
+
('state', c_uint * 16),
|
| 783 |
+
]
|
| 784 |
+
assert sizeof(MD2state_st) == 148, sizeof(MD2state_st)
|
| 785 |
+
assert alignment(MD2state_st) == 4, alignment(MD2state_st)
|
| 786 |
+
MD2_CTX = MD2state_st
|
| 787 |
+
class MD4state_st(Structure):
|
| 788 |
+
pass
|
| 789 |
+
MD4state_st._fields_ = [
|
| 790 |
+
('A', c_uint),
|
| 791 |
+
('B', c_uint),
|
| 792 |
+
('C', c_uint),
|
| 793 |
+
('D', c_uint),
|
| 794 |
+
('Nl', c_uint),
|
| 795 |
+
('Nh', c_uint),
|
| 796 |
+
('data', c_uint * 16),
|
| 797 |
+
('num', c_int),
|
| 798 |
+
]
|
| 799 |
+
assert sizeof(MD4state_st) == 92, sizeof(MD4state_st)
|
| 800 |
+
assert alignment(MD4state_st) == 4, alignment(MD4state_st)
|
| 801 |
+
MD4_CTX = MD4state_st
|
| 802 |
+
class MD5state_st(Structure):
|
| 803 |
+
pass
|
| 804 |
+
MD5state_st._fields_ = [
|
| 805 |
+
('A', c_uint),
|
| 806 |
+
('B', c_uint),
|
| 807 |
+
('C', c_uint),
|
| 808 |
+
('D', c_uint),
|
| 809 |
+
('Nl', c_uint),
|
| 810 |
+
('Nh', c_uint),
|
| 811 |
+
('data', c_uint * 16),
|
| 812 |
+
('num', c_int),
|
| 813 |
+
]
|
| 814 |
+
assert sizeof(MD5state_st) == 92, sizeof(MD5state_st)
|
| 815 |
+
assert alignment(MD5state_st) == 4, alignment(MD5state_st)
|
| 816 |
+
MD5_CTX = MD5state_st
|
| 817 |
+
class mdc2_ctx_st(Structure):
|
| 818 |
+
pass
|
| 819 |
+
mdc2_ctx_st._fields_ = [
|
| 820 |
+
('num', c_int),
|
| 821 |
+
('data', c_ubyte * 8),
|
| 822 |
+
('h', DES_cblock),
|
| 823 |
+
('hh', DES_cblock),
|
| 824 |
+
('pad_type', c_int),
|
| 825 |
+
]
|
| 826 |
+
assert sizeof(mdc2_ctx_st) == 32, sizeof(mdc2_ctx_st)
|
| 827 |
+
assert alignment(mdc2_ctx_st) == 4, alignment(mdc2_ctx_st)
|
| 828 |
+
MDC2_CTX = mdc2_ctx_st
|
| 829 |
+
class obj_name_st(Structure):
|
| 830 |
+
pass
|
| 831 |
+
obj_name_st._fields_ = [
|
| 832 |
+
('type', c_int),
|
| 833 |
+
('alias', c_int),
|
| 834 |
+
('name', STRING),
|
| 835 |
+
('data', STRING),
|
| 836 |
+
]
|
| 837 |
+
assert sizeof(obj_name_st) == 16, sizeof(obj_name_st)
|
| 838 |
+
assert alignment(obj_name_st) == 4, alignment(obj_name_st)
|
| 839 |
+
OBJ_NAME = obj_name_st
|
| 840 |
+
ASN1_TIME = asn1_string_st
|
| 841 |
+
ASN1_NULL = c_int
|
| 842 |
+
EVP_PKEY = evp_pkey_st
|
| 843 |
+
class x509_st(Structure):
|
| 844 |
+
pass
|
| 845 |
+
X509 = x509_st
|
| 846 |
+
class X509_algor_st(Structure):
|
| 847 |
+
pass
|
| 848 |
+
X509_ALGOR = X509_algor_st
|
| 849 |
+
class X509_crl_st(Structure):
|
| 850 |
+
pass
|
| 851 |
+
X509_CRL = X509_crl_st
|
| 852 |
+
class X509_name_st(Structure):
|
| 853 |
+
pass
|
| 854 |
+
X509_NAME = X509_name_st
|
| 855 |
+
class x509_store_st(Structure):
|
| 856 |
+
pass
|
| 857 |
+
X509_STORE = x509_store_st
|
| 858 |
+
class x509_store_ctx_st(Structure):
|
| 859 |
+
pass
|
| 860 |
+
X509_STORE_CTX = x509_store_ctx_st
|
| 861 |
+
engine_st._fields_ = [
|
| 862 |
+
]
|
| 863 |
+
class PEM_Encode_Seal_st(Structure):
|
| 864 |
+
pass
|
| 865 |
+
PEM_Encode_Seal_st._fields_ = [
|
| 866 |
+
('encode', EVP_ENCODE_CTX),
|
| 867 |
+
('md', EVP_MD_CTX),
|
| 868 |
+
('cipher', EVP_CIPHER_CTX),
|
| 869 |
+
]
|
| 870 |
+
assert sizeof(PEM_Encode_Seal_st) == 252, sizeof(PEM_Encode_Seal_st)
|
| 871 |
+
assert alignment(PEM_Encode_Seal_st) == 4, alignment(PEM_Encode_Seal_st)
|
| 872 |
+
PEM_ENCODE_SEAL_CTX = PEM_Encode_Seal_st
|
| 873 |
+
class pem_recip_st(Structure):
|
| 874 |
+
pass
|
| 875 |
+
pem_recip_st._fields_ = [
|
| 876 |
+
('name', STRING),
|
| 877 |
+
('dn', POINTER(X509_NAME)),
|
| 878 |
+
('cipher', c_int),
|
| 879 |
+
('key_enc', c_int),
|
| 880 |
+
]
|
| 881 |
+
assert sizeof(pem_recip_st) == 16, sizeof(pem_recip_st)
|
| 882 |
+
assert alignment(pem_recip_st) == 4, alignment(pem_recip_st)
|
| 883 |
+
PEM_USER = pem_recip_st
|
| 884 |
+
class pem_ctx_st(Structure):
|
| 885 |
+
pass
|
| 886 |
+
class N10pem_ctx_st4DOLLAR_16E(Structure):
|
| 887 |
+
pass
|
| 888 |
+
N10pem_ctx_st4DOLLAR_16E._fields_ = [
|
| 889 |
+
('version', c_int),
|
| 890 |
+
('mode', c_int),
|
| 891 |
+
]
|
| 892 |
+
assert sizeof(N10pem_ctx_st4DOLLAR_16E) == 8, sizeof(N10pem_ctx_st4DOLLAR_16E)
|
| 893 |
+
assert alignment(N10pem_ctx_st4DOLLAR_16E) == 4, alignment(N10pem_ctx_st4DOLLAR_16E)
|
| 894 |
+
class N10pem_ctx_st4DOLLAR_17E(Structure):
|
| 895 |
+
pass
|
| 896 |
+
N10pem_ctx_st4DOLLAR_17E._fields_ = [
|
| 897 |
+
('cipher', c_int),
|
| 898 |
+
]
|
| 899 |
+
assert sizeof(N10pem_ctx_st4DOLLAR_17E) == 4, sizeof(N10pem_ctx_st4DOLLAR_17E)
|
| 900 |
+
assert alignment(N10pem_ctx_st4DOLLAR_17E) == 4, alignment(N10pem_ctx_st4DOLLAR_17E)
|
| 901 |
+
pem_ctx_st._fields_ = [
|
| 902 |
+
('type', c_int),
|
| 903 |
+
('proc_type', N10pem_ctx_st4DOLLAR_16E),
|
| 904 |
+
('domain', STRING),
|
| 905 |
+
('DEK_info', N10pem_ctx_st4DOLLAR_17E),
|
| 906 |
+
('originator', POINTER(PEM_USER)),
|
| 907 |
+
('num_recipient', c_int),
|
| 908 |
+
('recipient', POINTER(POINTER(PEM_USER))),
|
| 909 |
+
('x509_chain', POINTER(STACK)),
|
| 910 |
+
('md', POINTER(EVP_MD)),
|
| 911 |
+
('md_enc', c_int),
|
| 912 |
+
('md_len', c_int),
|
| 913 |
+
('md_data', STRING),
|
| 914 |
+
('dec', POINTER(EVP_CIPHER)),
|
| 915 |
+
('key_len', c_int),
|
| 916 |
+
('key', POINTER(c_ubyte)),
|
| 917 |
+
('data_enc', c_int),
|
| 918 |
+
('data_len', c_int),
|
| 919 |
+
('data', POINTER(c_ubyte)),
|
| 920 |
+
]
|
| 921 |
+
assert sizeof(pem_ctx_st) == 76, sizeof(pem_ctx_st)
|
| 922 |
+
assert alignment(pem_ctx_st) == 4, alignment(pem_ctx_st)
|
| 923 |
+
PEM_CTX = pem_ctx_st
|
| 924 |
+
pem_password_cb = CFUNCTYPE(c_int, STRING, c_int, c_int, c_void_p)
|
| 925 |
+
class pkcs7_issuer_and_serial_st(Structure):
|
| 926 |
+
pass
|
| 927 |
+
pkcs7_issuer_and_serial_st._fields_ = [
|
| 928 |
+
('issuer', POINTER(X509_NAME)),
|
| 929 |
+
('serial', POINTER(ASN1_INTEGER)),
|
| 930 |
+
]
|
| 931 |
+
assert sizeof(pkcs7_issuer_and_serial_st) == 8, sizeof(pkcs7_issuer_and_serial_st)
|
| 932 |
+
assert alignment(pkcs7_issuer_and_serial_st) == 4, alignment(pkcs7_issuer_and_serial_st)
|
| 933 |
+
PKCS7_ISSUER_AND_SERIAL = pkcs7_issuer_and_serial_st
|
| 934 |
+
class pkcs7_signer_info_st(Structure):
|
| 935 |
+
pass
|
| 936 |
+
pkcs7_signer_info_st._fields_ = [
|
| 937 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 938 |
+
('issuer_and_serial', POINTER(PKCS7_ISSUER_AND_SERIAL)),
|
| 939 |
+
('digest_alg', POINTER(X509_ALGOR)),
|
| 940 |
+
('auth_attr', POINTER(STACK)),
|
| 941 |
+
('digest_enc_alg', POINTER(X509_ALGOR)),
|
| 942 |
+
('enc_digest', POINTER(ASN1_OCTET_STRING)),
|
| 943 |
+
('unauth_attr', POINTER(STACK)),
|
| 944 |
+
('pkey', POINTER(EVP_PKEY)),
|
| 945 |
+
]
|
| 946 |
+
assert sizeof(pkcs7_signer_info_st) == 32, sizeof(pkcs7_signer_info_st)
|
| 947 |
+
assert alignment(pkcs7_signer_info_st) == 4, alignment(pkcs7_signer_info_st)
|
| 948 |
+
PKCS7_SIGNER_INFO = pkcs7_signer_info_st
|
| 949 |
+
class pkcs7_recip_info_st(Structure):
|
| 950 |
+
pass
|
| 951 |
+
pkcs7_recip_info_st._fields_ = [
|
| 952 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 953 |
+
('issuer_and_serial', POINTER(PKCS7_ISSUER_AND_SERIAL)),
|
| 954 |
+
('key_enc_algor', POINTER(X509_ALGOR)),
|
| 955 |
+
('enc_key', POINTER(ASN1_OCTET_STRING)),
|
| 956 |
+
('cert', POINTER(X509)),
|
| 957 |
+
]
|
| 958 |
+
assert sizeof(pkcs7_recip_info_st) == 20, sizeof(pkcs7_recip_info_st)
|
| 959 |
+
assert alignment(pkcs7_recip_info_st) == 4, alignment(pkcs7_recip_info_st)
|
| 960 |
+
PKCS7_RECIP_INFO = pkcs7_recip_info_st
|
| 961 |
+
class pkcs7_signed_st(Structure):
|
| 962 |
+
pass
|
| 963 |
+
class pkcs7_st(Structure):
|
| 964 |
+
pass
|
| 965 |
+
pkcs7_signed_st._fields_ = [
|
| 966 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 967 |
+
('md_algs', POINTER(STACK)),
|
| 968 |
+
('cert', POINTER(STACK)),
|
| 969 |
+
('crl', POINTER(STACK)),
|
| 970 |
+
('signer_info', POINTER(STACK)),
|
| 971 |
+
('contents', POINTER(pkcs7_st)),
|
| 972 |
+
]
|
| 973 |
+
assert sizeof(pkcs7_signed_st) == 24, sizeof(pkcs7_signed_st)
|
| 974 |
+
assert alignment(pkcs7_signed_st) == 4, alignment(pkcs7_signed_st)
|
| 975 |
+
PKCS7_SIGNED = pkcs7_signed_st
|
| 976 |
+
class pkcs7_enc_content_st(Structure):
|
| 977 |
+
pass
|
| 978 |
+
pkcs7_enc_content_st._fields_ = [
|
| 979 |
+
('content_type', POINTER(ASN1_OBJECT)),
|
| 980 |
+
('algorithm', POINTER(X509_ALGOR)),
|
| 981 |
+
('enc_data', POINTER(ASN1_OCTET_STRING)),
|
| 982 |
+
('cipher', POINTER(EVP_CIPHER)),
|
| 983 |
+
]
|
| 984 |
+
assert sizeof(pkcs7_enc_content_st) == 16, sizeof(pkcs7_enc_content_st)
|
| 985 |
+
assert alignment(pkcs7_enc_content_st) == 4, alignment(pkcs7_enc_content_st)
|
| 986 |
+
PKCS7_ENC_CONTENT = pkcs7_enc_content_st
|
| 987 |
+
class pkcs7_enveloped_st(Structure):
|
| 988 |
+
pass
|
| 989 |
+
pkcs7_enveloped_st._fields_ = [
|
| 990 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 991 |
+
('recipientinfo', POINTER(STACK)),
|
| 992 |
+
('enc_data', POINTER(PKCS7_ENC_CONTENT)),
|
| 993 |
+
]
|
| 994 |
+
assert sizeof(pkcs7_enveloped_st) == 12, sizeof(pkcs7_enveloped_st)
|
| 995 |
+
assert alignment(pkcs7_enveloped_st) == 4, alignment(pkcs7_enveloped_st)
|
| 996 |
+
PKCS7_ENVELOPE = pkcs7_enveloped_st
|
| 997 |
+
class pkcs7_signedandenveloped_st(Structure):
|
| 998 |
+
pass
|
| 999 |
+
pkcs7_signedandenveloped_st._fields_ = [
|
| 1000 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1001 |
+
('md_algs', POINTER(STACK)),
|
| 1002 |
+
('cert', POINTER(STACK)),
|
| 1003 |
+
('crl', POINTER(STACK)),
|
| 1004 |
+
('signer_info', POINTER(STACK)),
|
| 1005 |
+
('enc_data', POINTER(PKCS7_ENC_CONTENT)),
|
| 1006 |
+
('recipientinfo', POINTER(STACK)),
|
| 1007 |
+
]
|
| 1008 |
+
assert sizeof(pkcs7_signedandenveloped_st) == 28, sizeof(pkcs7_signedandenveloped_st)
|
| 1009 |
+
assert alignment(pkcs7_signedandenveloped_st) == 4, alignment(pkcs7_signedandenveloped_st)
|
| 1010 |
+
PKCS7_SIGN_ENVELOPE = pkcs7_signedandenveloped_st
|
| 1011 |
+
class pkcs7_digest_st(Structure):
|
| 1012 |
+
pass
|
| 1013 |
+
pkcs7_digest_st._fields_ = [
|
| 1014 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1015 |
+
('md', POINTER(X509_ALGOR)),
|
| 1016 |
+
('contents', POINTER(pkcs7_st)),
|
| 1017 |
+
('digest', POINTER(ASN1_OCTET_STRING)),
|
| 1018 |
+
]
|
| 1019 |
+
assert sizeof(pkcs7_digest_st) == 16, sizeof(pkcs7_digest_st)
|
| 1020 |
+
assert alignment(pkcs7_digest_st) == 4, alignment(pkcs7_digest_st)
|
| 1021 |
+
PKCS7_DIGEST = pkcs7_digest_st
|
| 1022 |
+
class pkcs7_encrypted_st(Structure):
|
| 1023 |
+
pass
|
| 1024 |
+
pkcs7_encrypted_st._fields_ = [
|
| 1025 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1026 |
+
('enc_data', POINTER(PKCS7_ENC_CONTENT)),
|
| 1027 |
+
]
|
| 1028 |
+
assert sizeof(pkcs7_encrypted_st) == 8, sizeof(pkcs7_encrypted_st)
|
| 1029 |
+
assert alignment(pkcs7_encrypted_st) == 4, alignment(pkcs7_encrypted_st)
|
| 1030 |
+
PKCS7_ENCRYPT = pkcs7_encrypted_st
|
| 1031 |
+
class N8pkcs7_st4DOLLAR_15E(Union):
|
| 1032 |
+
pass
|
| 1033 |
+
N8pkcs7_st4DOLLAR_15E._fields_ = [
|
| 1034 |
+
('ptr', STRING),
|
| 1035 |
+
('data', POINTER(ASN1_OCTET_STRING)),
|
| 1036 |
+
('sign', POINTER(PKCS7_SIGNED)),
|
| 1037 |
+
('enveloped', POINTER(PKCS7_ENVELOPE)),
|
| 1038 |
+
('signed_and_enveloped', POINTER(PKCS7_SIGN_ENVELOPE)),
|
| 1039 |
+
('digest', POINTER(PKCS7_DIGEST)),
|
| 1040 |
+
('encrypted', POINTER(PKCS7_ENCRYPT)),
|
| 1041 |
+
('other', POINTER(ASN1_TYPE)),
|
| 1042 |
+
]
|
| 1043 |
+
assert sizeof(N8pkcs7_st4DOLLAR_15E) == 4, sizeof(N8pkcs7_st4DOLLAR_15E)
|
| 1044 |
+
assert alignment(N8pkcs7_st4DOLLAR_15E) == 4, alignment(N8pkcs7_st4DOLLAR_15E)
|
| 1045 |
+
pkcs7_st._fields_ = [
|
| 1046 |
+
('asn1', POINTER(c_ubyte)),
|
| 1047 |
+
('length', c_long),
|
| 1048 |
+
('state', c_int),
|
| 1049 |
+
('detached', c_int),
|
| 1050 |
+
('type', POINTER(ASN1_OBJECT)),
|
| 1051 |
+
('d', N8pkcs7_st4DOLLAR_15E),
|
| 1052 |
+
]
|
| 1053 |
+
assert sizeof(pkcs7_st) == 24, sizeof(pkcs7_st)
|
| 1054 |
+
assert alignment(pkcs7_st) == 4, alignment(pkcs7_st)
|
| 1055 |
+
PKCS7 = pkcs7_st
|
| 1056 |
+
class rc2_key_st(Structure):
|
| 1057 |
+
pass
|
| 1058 |
+
rc2_key_st._fields_ = [
|
| 1059 |
+
('data', c_uint * 64),
|
| 1060 |
+
]
|
| 1061 |
+
assert sizeof(rc2_key_st) == 256, sizeof(rc2_key_st)
|
| 1062 |
+
assert alignment(rc2_key_st) == 4, alignment(rc2_key_st)
|
| 1063 |
+
RC2_KEY = rc2_key_st
|
| 1064 |
+
class rc4_key_st(Structure):
|
| 1065 |
+
pass
|
| 1066 |
+
rc4_key_st._fields_ = [
|
| 1067 |
+
('x', c_ubyte),
|
| 1068 |
+
('y', c_ubyte),
|
| 1069 |
+
('data', c_ubyte * 256),
|
| 1070 |
+
]
|
| 1071 |
+
assert sizeof(rc4_key_st) == 258, sizeof(rc4_key_st)
|
| 1072 |
+
assert alignment(rc4_key_st) == 1, alignment(rc4_key_st)
|
| 1073 |
+
RC4_KEY = rc4_key_st
|
| 1074 |
+
class rc5_key_st(Structure):
|
| 1075 |
+
pass
|
| 1076 |
+
rc5_key_st._fields_ = [
|
| 1077 |
+
('rounds', c_int),
|
| 1078 |
+
('data', c_ulong * 34),
|
| 1079 |
+
]
|
| 1080 |
+
assert sizeof(rc5_key_st) == 140, sizeof(rc5_key_st)
|
| 1081 |
+
assert alignment(rc5_key_st) == 4, alignment(rc5_key_st)
|
| 1082 |
+
RC5_32_KEY = rc5_key_st
|
| 1083 |
+
class RIPEMD160state_st(Structure):
|
| 1084 |
+
pass
|
| 1085 |
+
RIPEMD160state_st._fields_ = [
|
| 1086 |
+
('A', c_uint),
|
| 1087 |
+
('B', c_uint),
|
| 1088 |
+
('C', c_uint),
|
| 1089 |
+
('D', c_uint),
|
| 1090 |
+
('E', c_uint),
|
| 1091 |
+
('Nl', c_uint),
|
| 1092 |
+
('Nh', c_uint),
|
| 1093 |
+
('data', c_uint * 16),
|
| 1094 |
+
('num', c_int),
|
| 1095 |
+
]
|
| 1096 |
+
assert sizeof(RIPEMD160state_st) == 96, sizeof(RIPEMD160state_st)
|
| 1097 |
+
assert alignment(RIPEMD160state_st) == 4, alignment(RIPEMD160state_st)
|
| 1098 |
+
RIPEMD160_CTX = RIPEMD160state_st
|
| 1099 |
+
RSA = rsa_st
|
| 1100 |
+
class rsa_meth_st(Structure):
|
| 1101 |
+
pass
|
| 1102 |
+
rsa_meth_st._fields_ = [
|
| 1103 |
+
('name', STRING),
|
| 1104 |
+
('rsa_pub_enc', CFUNCTYPE(c_int, c_int, POINTER(c_ubyte), POINTER(c_ubyte), POINTER(RSA), c_int)),
|
| 1105 |
+
('rsa_pub_dec', CFUNCTYPE(c_int, c_int, POINTER(c_ubyte), POINTER(c_ubyte), POINTER(RSA), c_int)),
|
| 1106 |
+
('rsa_priv_enc', CFUNCTYPE(c_int, c_int, POINTER(c_ubyte), POINTER(c_ubyte), POINTER(RSA), c_int)),
|
| 1107 |
+
('rsa_priv_dec', CFUNCTYPE(c_int, c_int, POINTER(c_ubyte), POINTER(c_ubyte), POINTER(RSA), c_int)),
|
| 1108 |
+
('rsa_mod_exp', CFUNCTYPE(c_int, POINTER(BIGNUM), POINTER(BIGNUM), POINTER(RSA))),
|
| 1109 |
+
('bn_mod_exp', CFUNCTYPE(c_int, POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BIGNUM), POINTER(BN_CTX), POINTER(BN_MONT_CTX))),
|
| 1110 |
+
('init', CFUNCTYPE(c_int, POINTER(RSA))),
|
| 1111 |
+
('finish', CFUNCTYPE(c_int, POINTER(RSA))),
|
| 1112 |
+
('flags', c_int),
|
| 1113 |
+
('app_data', STRING),
|
| 1114 |
+
('rsa_sign', CFUNCTYPE(c_int, c_int, POINTER(c_ubyte), c_uint, POINTER(c_ubyte), POINTER(c_uint), POINTER(RSA))),
|
| 1115 |
+
('rsa_verify', CFUNCTYPE(c_int, c_int, POINTER(c_ubyte), c_uint, POINTER(c_ubyte), c_uint, POINTER(RSA))),
|
| 1116 |
+
]
|
| 1117 |
+
assert sizeof(rsa_meth_st) == 52, sizeof(rsa_meth_st)
|
| 1118 |
+
assert alignment(rsa_meth_st) == 4, alignment(rsa_meth_st)
|
| 1119 |
+
RSA_METHOD = rsa_meth_st
|
| 1120 |
+
rsa_st._fields_ = [
|
| 1121 |
+
('pad', c_int),
|
| 1122 |
+
('version', c_long),
|
| 1123 |
+
('meth', POINTER(RSA_METHOD)),
|
| 1124 |
+
('engine', POINTER(ENGINE)),
|
| 1125 |
+
('n', POINTER(BIGNUM)),
|
| 1126 |
+
('e', POINTER(BIGNUM)),
|
| 1127 |
+
('d', POINTER(BIGNUM)),
|
| 1128 |
+
('p', POINTER(BIGNUM)),
|
| 1129 |
+
('q', POINTER(BIGNUM)),
|
| 1130 |
+
('dmp1', POINTER(BIGNUM)),
|
| 1131 |
+
('dmq1', POINTER(BIGNUM)),
|
| 1132 |
+
('iqmp', POINTER(BIGNUM)),
|
| 1133 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 1134 |
+
('references', c_int),
|
| 1135 |
+
('flags', c_int),
|
| 1136 |
+
('_method_mod_n', POINTER(BN_MONT_CTX)),
|
| 1137 |
+
('_method_mod_p', POINTER(BN_MONT_CTX)),
|
| 1138 |
+
('_method_mod_q', POINTER(BN_MONT_CTX)),
|
| 1139 |
+
('bignum_data', STRING),
|
| 1140 |
+
('blinding', POINTER(BN_BLINDING)),
|
| 1141 |
+
]
|
| 1142 |
+
assert sizeof(rsa_st) == 84, sizeof(rsa_st)
|
| 1143 |
+
assert alignment(rsa_st) == 4, alignment(rsa_st)
|
| 1144 |
+
openssl_fptr = CFUNCTYPE(None)
|
| 1145 |
+
class SHAstate_st(Structure):
|
| 1146 |
+
pass
|
| 1147 |
+
SHAstate_st._fields_ = [
|
| 1148 |
+
('h0', c_uint),
|
| 1149 |
+
('h1', c_uint),
|
| 1150 |
+
('h2', c_uint),
|
| 1151 |
+
('h3', c_uint),
|
| 1152 |
+
('h4', c_uint),
|
| 1153 |
+
('Nl', c_uint),
|
| 1154 |
+
('Nh', c_uint),
|
| 1155 |
+
('data', c_uint * 16),
|
| 1156 |
+
('num', c_int),
|
| 1157 |
+
]
|
| 1158 |
+
assert sizeof(SHAstate_st) == 96, sizeof(SHAstate_st)
|
| 1159 |
+
assert alignment(SHAstate_st) == 4, alignment(SHAstate_st)
|
| 1160 |
+
SHA_CTX = SHAstate_st
|
| 1161 |
+
class ssl_st(Structure):
|
| 1162 |
+
pass
|
| 1163 |
+
ssl_crock_st = POINTER(ssl_st)
|
| 1164 |
+
class ssl_cipher_st(Structure):
|
| 1165 |
+
pass
|
| 1166 |
+
ssl_cipher_st._fields_ = [
|
| 1167 |
+
('valid', c_int),
|
| 1168 |
+
('name', STRING),
|
| 1169 |
+
('id', c_ulong),
|
| 1170 |
+
('algorithms', c_ulong),
|
| 1171 |
+
('algo_strength', c_ulong),
|
| 1172 |
+
('algorithm2', c_ulong),
|
| 1173 |
+
('strength_bits', c_int),
|
| 1174 |
+
('alg_bits', c_int),
|
| 1175 |
+
('mask', c_ulong),
|
| 1176 |
+
('mask_strength', c_ulong),
|
| 1177 |
+
]
|
| 1178 |
+
assert sizeof(ssl_cipher_st) == 40, sizeof(ssl_cipher_st)
|
| 1179 |
+
assert alignment(ssl_cipher_st) == 4, alignment(ssl_cipher_st)
|
| 1180 |
+
SSL_CIPHER = ssl_cipher_st
|
| 1181 |
+
SSL = ssl_st
|
| 1182 |
+
class ssl_ctx_st(Structure):
|
| 1183 |
+
pass
|
| 1184 |
+
SSL_CTX = ssl_ctx_st
|
| 1185 |
+
class ssl_method_st(Structure):
|
| 1186 |
+
pass
|
| 1187 |
+
class ssl3_enc_method(Structure):
|
| 1188 |
+
pass
|
| 1189 |
+
ssl_method_st._fields_ = [
|
| 1190 |
+
('version', c_int),
|
| 1191 |
+
('ssl_new', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1192 |
+
('ssl_clear', CFUNCTYPE(None, POINTER(SSL))),
|
| 1193 |
+
('ssl_free', CFUNCTYPE(None, POINTER(SSL))),
|
| 1194 |
+
('ssl_accept', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1195 |
+
('ssl_connect', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1196 |
+
('ssl_read', CFUNCTYPE(c_int, POINTER(SSL), c_void_p, c_int)),
|
| 1197 |
+
('ssl_peek', CFUNCTYPE(c_int, POINTER(SSL), c_void_p, c_int)),
|
| 1198 |
+
('ssl_write', CFUNCTYPE(c_int, POINTER(SSL), c_void_p, c_int)),
|
| 1199 |
+
('ssl_shutdown', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1200 |
+
('ssl_renegotiate', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1201 |
+
('ssl_renegotiate_check', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1202 |
+
('ssl_ctrl', CFUNCTYPE(c_long, POINTER(SSL), c_int, c_long, c_void_p)),
|
| 1203 |
+
('ssl_ctx_ctrl', CFUNCTYPE(c_long, POINTER(SSL_CTX), c_int, c_long, c_void_p)),
|
| 1204 |
+
('get_cipher_by_char', CFUNCTYPE(POINTER(SSL_CIPHER), POINTER(c_ubyte))),
|
| 1205 |
+
('put_cipher_by_char', CFUNCTYPE(c_int, POINTER(SSL_CIPHER), POINTER(c_ubyte))),
|
| 1206 |
+
('ssl_pending', CFUNCTYPE(c_int, POINTER(SSL))),
|
| 1207 |
+
('num_ciphers', CFUNCTYPE(c_int)),
|
| 1208 |
+
('get_cipher', CFUNCTYPE(POINTER(SSL_CIPHER), c_uint)),
|
| 1209 |
+
('get_ssl_method', CFUNCTYPE(POINTER(ssl_method_st), c_int)),
|
| 1210 |
+
('get_timeout', CFUNCTYPE(c_long)),
|
| 1211 |
+
('ssl3_enc', POINTER(ssl3_enc_method)),
|
| 1212 |
+
('ssl_version', CFUNCTYPE(c_int)),
|
| 1213 |
+
('ssl_callback_ctrl', CFUNCTYPE(c_long, POINTER(SSL), c_int, CFUNCTYPE(None))),
|
| 1214 |
+
('ssl_ctx_callback_ctrl', CFUNCTYPE(c_long, POINTER(SSL_CTX), c_int, CFUNCTYPE(None))),
|
| 1215 |
+
]
|
| 1216 |
+
assert sizeof(ssl_method_st) == 100, sizeof(ssl_method_st)
|
| 1217 |
+
assert alignment(ssl_method_st) == 4, alignment(ssl_method_st)
|
| 1218 |
+
ssl3_enc_method._fields_ = [
|
| 1219 |
+
]
|
| 1220 |
+
SSL_METHOD = ssl_method_st
|
| 1221 |
+
class ssl_session_st(Structure):
|
| 1222 |
+
pass
|
| 1223 |
+
class sess_cert_st(Structure):
|
| 1224 |
+
pass
|
| 1225 |
+
ssl_session_st._fields_ = [
|
| 1226 |
+
('ssl_version', c_int),
|
| 1227 |
+
('key_arg_length', c_uint),
|
| 1228 |
+
('key_arg', c_ubyte * 8),
|
| 1229 |
+
('master_key_length', c_int),
|
| 1230 |
+
('master_key', c_ubyte * 48),
|
| 1231 |
+
('session_id_length', c_uint),
|
| 1232 |
+
('session_id', c_ubyte * 32),
|
| 1233 |
+
('sid_ctx_length', c_uint),
|
| 1234 |
+
('sid_ctx', c_ubyte * 32),
|
| 1235 |
+
('not_resumable', c_int),
|
| 1236 |
+
('sess_cert', POINTER(sess_cert_st)),
|
| 1237 |
+
('peer', POINTER(X509)),
|
| 1238 |
+
('verify_result', c_long),
|
| 1239 |
+
('references', c_int),
|
| 1240 |
+
('timeout', c_long),
|
| 1241 |
+
('time', c_long),
|
| 1242 |
+
('compress_meth', c_int),
|
| 1243 |
+
('cipher', POINTER(SSL_CIPHER)),
|
| 1244 |
+
('cipher_id', c_ulong),
|
| 1245 |
+
('ciphers', POINTER(STACK)),
|
| 1246 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 1247 |
+
('prev', POINTER(ssl_session_st)),
|
| 1248 |
+
('next', POINTER(ssl_session_st)),
|
| 1249 |
+
]
|
| 1250 |
+
assert sizeof(ssl_session_st) == 200, sizeof(ssl_session_st)
|
| 1251 |
+
assert alignment(ssl_session_st) == 4, alignment(ssl_session_st)
|
| 1252 |
+
sess_cert_st._fields_ = [
|
| 1253 |
+
]
|
| 1254 |
+
SSL_SESSION = ssl_session_st
|
| 1255 |
+
GEN_SESSION_CB = CFUNCTYPE(c_int, POINTER(SSL), POINTER(c_ubyte), POINTER(c_uint))
|
| 1256 |
+
class ssl_comp_st(Structure):
|
| 1257 |
+
pass
|
| 1258 |
+
ssl_comp_st._fields_ = [
|
| 1259 |
+
('id', c_int),
|
| 1260 |
+
('name', STRING),
|
| 1261 |
+
('method', POINTER(COMP_METHOD)),
|
| 1262 |
+
]
|
| 1263 |
+
assert sizeof(ssl_comp_st) == 12, sizeof(ssl_comp_st)
|
| 1264 |
+
assert alignment(ssl_comp_st) == 4, alignment(ssl_comp_st)
|
| 1265 |
+
SSL_COMP = ssl_comp_st
|
| 1266 |
+
class N10ssl_ctx_st4DOLLAR_18E(Structure):
|
| 1267 |
+
pass
|
| 1268 |
+
N10ssl_ctx_st4DOLLAR_18E._fields_ = [
|
| 1269 |
+
('sess_connect', c_int),
|
| 1270 |
+
('sess_connect_renegotiate', c_int),
|
| 1271 |
+
('sess_connect_good', c_int),
|
| 1272 |
+
('sess_accept', c_int),
|
| 1273 |
+
('sess_accept_renegotiate', c_int),
|
| 1274 |
+
('sess_accept_good', c_int),
|
| 1275 |
+
('sess_miss', c_int),
|
| 1276 |
+
('sess_timeout', c_int),
|
| 1277 |
+
('sess_cache_full', c_int),
|
| 1278 |
+
('sess_hit', c_int),
|
| 1279 |
+
('sess_cb_hit', c_int),
|
| 1280 |
+
]
|
| 1281 |
+
assert sizeof(N10ssl_ctx_st4DOLLAR_18E) == 44, sizeof(N10ssl_ctx_st4DOLLAR_18E)
|
| 1282 |
+
assert alignment(N10ssl_ctx_st4DOLLAR_18E) == 4, alignment(N10ssl_ctx_st4DOLLAR_18E)
|
| 1283 |
+
class cert_st(Structure):
|
| 1284 |
+
pass
|
| 1285 |
+
ssl_ctx_st._fields_ = [
|
| 1286 |
+
('method', POINTER(SSL_METHOD)),
|
| 1287 |
+
('cipher_list', POINTER(STACK)),
|
| 1288 |
+
('cipher_list_by_id', POINTER(STACK)),
|
| 1289 |
+
('cert_store', POINTER(x509_store_st)),
|
| 1290 |
+
('sessions', POINTER(lhash_st)),
|
| 1291 |
+
('session_cache_size', c_ulong),
|
| 1292 |
+
('session_cache_head', POINTER(ssl_session_st)),
|
| 1293 |
+
('session_cache_tail', POINTER(ssl_session_st)),
|
| 1294 |
+
('session_cache_mode', c_int),
|
| 1295 |
+
('session_timeout', c_long),
|
| 1296 |
+
('new_session_cb', CFUNCTYPE(c_int, POINTER(ssl_st), POINTER(SSL_SESSION))),
|
| 1297 |
+
('remove_session_cb', CFUNCTYPE(None, POINTER(ssl_ctx_st), POINTER(SSL_SESSION))),
|
| 1298 |
+
('get_session_cb', CFUNCTYPE(POINTER(SSL_SESSION), POINTER(ssl_st), POINTER(c_ubyte), c_int, POINTER(c_int))),
|
| 1299 |
+
('stats', N10ssl_ctx_st4DOLLAR_18E),
|
| 1300 |
+
('references', c_int),
|
| 1301 |
+
('app_verify_callback', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), c_void_p)),
|
| 1302 |
+
('app_verify_arg', c_void_p),
|
| 1303 |
+
('default_passwd_callback', POINTER(pem_password_cb)),
|
| 1304 |
+
('default_passwd_callback_userdata', c_void_p),
|
| 1305 |
+
('client_cert_cb', CFUNCTYPE(c_int, POINTER(SSL), POINTER(POINTER(X509)), POINTER(POINTER(EVP_PKEY)))),
|
| 1306 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 1307 |
+
('rsa_md5', POINTER(EVP_MD)),
|
| 1308 |
+
('md5', POINTER(EVP_MD)),
|
| 1309 |
+
('sha1', POINTER(EVP_MD)),
|
| 1310 |
+
('extra_certs', POINTER(STACK)),
|
| 1311 |
+
('comp_methods', POINTER(STACK)),
|
| 1312 |
+
('info_callback', CFUNCTYPE(None, POINTER(SSL), c_int, c_int)),
|
| 1313 |
+
('client_CA', POINTER(STACK)),
|
| 1314 |
+
('options', c_ulong),
|
| 1315 |
+
('mode', c_ulong),
|
| 1316 |
+
('max_cert_list', c_long),
|
| 1317 |
+
('cert', POINTER(cert_st)),
|
| 1318 |
+
('read_ahead', c_int),
|
| 1319 |
+
('msg_callback', CFUNCTYPE(None, c_int, c_int, c_int, c_void_p, c_ulong, POINTER(SSL), c_void_p)),
|
| 1320 |
+
('msg_callback_arg', c_void_p),
|
| 1321 |
+
('verify_mode', c_int),
|
| 1322 |
+
('verify_depth', c_int),
|
| 1323 |
+
('sid_ctx_length', c_uint),
|
| 1324 |
+
('sid_ctx', c_ubyte * 32),
|
| 1325 |
+
('default_verify_callback', CFUNCTYPE(c_int, c_int, POINTER(X509_STORE_CTX))),
|
| 1326 |
+
('generate_session_id', GEN_SESSION_CB),
|
| 1327 |
+
('purpose', c_int),
|
| 1328 |
+
('trust', c_int),
|
| 1329 |
+
('quiet_shutdown', c_int),
|
| 1330 |
+
]
|
| 1331 |
+
assert sizeof(ssl_ctx_st) == 248, sizeof(ssl_ctx_st)
|
| 1332 |
+
assert alignment(ssl_ctx_st) == 4, alignment(ssl_ctx_st)
|
| 1333 |
+
cert_st._fields_ = [
|
| 1334 |
+
]
|
| 1335 |
+
class ssl2_state_st(Structure):
|
| 1336 |
+
pass
|
| 1337 |
+
class ssl3_state_st(Structure):
|
| 1338 |
+
pass
|
| 1339 |
+
ssl_st._fields_ = [
|
| 1340 |
+
('version', c_int),
|
| 1341 |
+
('type', c_int),
|
| 1342 |
+
('method', POINTER(SSL_METHOD)),
|
| 1343 |
+
('rbio', POINTER(BIO)),
|
| 1344 |
+
('wbio', POINTER(BIO)),
|
| 1345 |
+
('bbio', POINTER(BIO)),
|
| 1346 |
+
('rwstate', c_int),
|
| 1347 |
+
('in_handshake', c_int),
|
| 1348 |
+
('handshake_func', CFUNCTYPE(c_int)),
|
| 1349 |
+
('server', c_int),
|
| 1350 |
+
('new_session', c_int),
|
| 1351 |
+
('quiet_shutdown', c_int),
|
| 1352 |
+
('shutdown', c_int),
|
| 1353 |
+
('state', c_int),
|
| 1354 |
+
('rstate', c_int),
|
| 1355 |
+
('init_buf', POINTER(BUF_MEM)),
|
| 1356 |
+
('init_msg', c_void_p),
|
| 1357 |
+
('init_num', c_int),
|
| 1358 |
+
('init_off', c_int),
|
| 1359 |
+
('packet', POINTER(c_ubyte)),
|
| 1360 |
+
('packet_length', c_uint),
|
| 1361 |
+
('s2', POINTER(ssl2_state_st)),
|
| 1362 |
+
('s3', POINTER(ssl3_state_st)),
|
| 1363 |
+
('read_ahead', c_int),
|
| 1364 |
+
('msg_callback', CFUNCTYPE(None, c_int, c_int, c_int, c_void_p, c_ulong, POINTER(SSL), c_void_p)),
|
| 1365 |
+
('msg_callback_arg', c_void_p),
|
| 1366 |
+
('hit', c_int),
|
| 1367 |
+
('purpose', c_int),
|
| 1368 |
+
('trust', c_int),
|
| 1369 |
+
('cipher_list', POINTER(STACK)),
|
| 1370 |
+
('cipher_list_by_id', POINTER(STACK)),
|
| 1371 |
+
('enc_read_ctx', POINTER(EVP_CIPHER_CTX)),
|
| 1372 |
+
('read_hash', POINTER(EVP_MD)),
|
| 1373 |
+
('expand', POINTER(COMP_CTX)),
|
| 1374 |
+
('enc_write_ctx', POINTER(EVP_CIPHER_CTX)),
|
| 1375 |
+
('write_hash', POINTER(EVP_MD)),
|
| 1376 |
+
('compress', POINTER(COMP_CTX)),
|
| 1377 |
+
('cert', POINTER(cert_st)),
|
| 1378 |
+
('sid_ctx_length', c_uint),
|
| 1379 |
+
('sid_ctx', c_ubyte * 32),
|
| 1380 |
+
('session', POINTER(SSL_SESSION)),
|
| 1381 |
+
('generate_session_id', GEN_SESSION_CB),
|
| 1382 |
+
('verify_mode', c_int),
|
| 1383 |
+
('verify_depth', c_int),
|
| 1384 |
+
('verify_callback', CFUNCTYPE(c_int, c_int, POINTER(X509_STORE_CTX))),
|
| 1385 |
+
('info_callback', CFUNCTYPE(None, POINTER(SSL), c_int, c_int)),
|
| 1386 |
+
('error', c_int),
|
| 1387 |
+
('error_code', c_int),
|
| 1388 |
+
('ctx', POINTER(SSL_CTX)),
|
| 1389 |
+
('debug', c_int),
|
| 1390 |
+
('verify_result', c_long),
|
| 1391 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 1392 |
+
('client_CA', POINTER(STACK)),
|
| 1393 |
+
('references', c_int),
|
| 1394 |
+
('options', c_ulong),
|
| 1395 |
+
('mode', c_ulong),
|
| 1396 |
+
('max_cert_list', c_long),
|
| 1397 |
+
('first_packet', c_int),
|
| 1398 |
+
('client_version', c_int),
|
| 1399 |
+
]
|
| 1400 |
+
assert sizeof(ssl_st) == 268, sizeof(ssl_st)
|
| 1401 |
+
assert alignment(ssl_st) == 4, alignment(ssl_st)
|
| 1402 |
+
class N13ssl2_state_st4DOLLAR_19E(Structure):
|
| 1403 |
+
pass
|
| 1404 |
+
N13ssl2_state_st4DOLLAR_19E._fields_ = [
|
| 1405 |
+
('conn_id_length', c_uint),
|
| 1406 |
+
('cert_type', c_uint),
|
| 1407 |
+
('cert_length', c_uint),
|
| 1408 |
+
('csl', c_uint),
|
| 1409 |
+
('clear', c_uint),
|
| 1410 |
+
('enc', c_uint),
|
| 1411 |
+
('ccl', c_ubyte * 32),
|
| 1412 |
+
('cipher_spec_length', c_uint),
|
| 1413 |
+
('session_id_length', c_uint),
|
| 1414 |
+
('clen', c_uint),
|
| 1415 |
+
('rlen', c_uint),
|
| 1416 |
+
]
|
| 1417 |
+
assert sizeof(N13ssl2_state_st4DOLLAR_19E) == 72, sizeof(N13ssl2_state_st4DOLLAR_19E)
|
| 1418 |
+
assert alignment(N13ssl2_state_st4DOLLAR_19E) == 4, alignment(N13ssl2_state_st4DOLLAR_19E)
|
| 1419 |
+
ssl2_state_st._fields_ = [
|
| 1420 |
+
('three_byte_header', c_int),
|
| 1421 |
+
('clear_text', c_int),
|
| 1422 |
+
('escape', c_int),
|
| 1423 |
+
('ssl2_rollback', c_int),
|
| 1424 |
+
('wnum', c_uint),
|
| 1425 |
+
('wpend_tot', c_int),
|
| 1426 |
+
('wpend_buf', POINTER(c_ubyte)),
|
| 1427 |
+
('wpend_off', c_int),
|
| 1428 |
+
('wpend_len', c_int),
|
| 1429 |
+
('wpend_ret', c_int),
|
| 1430 |
+
('rbuf_left', c_int),
|
| 1431 |
+
('rbuf_offs', c_int),
|
| 1432 |
+
('rbuf', POINTER(c_ubyte)),
|
| 1433 |
+
('wbuf', POINTER(c_ubyte)),
|
| 1434 |
+
('write_ptr', POINTER(c_ubyte)),
|
| 1435 |
+
('padding', c_uint),
|
| 1436 |
+
('rlength', c_uint),
|
| 1437 |
+
('ract_data_length', c_int),
|
| 1438 |
+
('wlength', c_uint),
|
| 1439 |
+
('wact_data_length', c_int),
|
| 1440 |
+
('ract_data', POINTER(c_ubyte)),
|
| 1441 |
+
('wact_data', POINTER(c_ubyte)),
|
| 1442 |
+
('mac_data', POINTER(c_ubyte)),
|
| 1443 |
+
('read_key', POINTER(c_ubyte)),
|
| 1444 |
+
('write_key', POINTER(c_ubyte)),
|
| 1445 |
+
('challenge_length', c_uint),
|
| 1446 |
+
('challenge', c_ubyte * 32),
|
| 1447 |
+
('conn_id_length', c_uint),
|
| 1448 |
+
('conn_id', c_ubyte * 16),
|
| 1449 |
+
('key_material_length', c_uint),
|
| 1450 |
+
('key_material', c_ubyte * 48),
|
| 1451 |
+
('read_sequence', c_ulong),
|
| 1452 |
+
('write_sequence', c_ulong),
|
| 1453 |
+
('tmp', N13ssl2_state_st4DOLLAR_19E),
|
| 1454 |
+
]
|
| 1455 |
+
assert sizeof(ssl2_state_st) == 288, sizeof(ssl2_state_st)
|
| 1456 |
+
assert alignment(ssl2_state_st) == 4, alignment(ssl2_state_st)
|
| 1457 |
+
SSL2_STATE = ssl2_state_st
|
| 1458 |
+
class ssl3_record_st(Structure):
|
| 1459 |
+
pass
|
| 1460 |
+
ssl3_record_st._fields_ = [
|
| 1461 |
+
('type', c_int),
|
| 1462 |
+
('length', c_uint),
|
| 1463 |
+
('off', c_uint),
|
| 1464 |
+
('data', POINTER(c_ubyte)),
|
| 1465 |
+
('input', POINTER(c_ubyte)),
|
| 1466 |
+
('comp', POINTER(c_ubyte)),
|
| 1467 |
+
]
|
| 1468 |
+
assert sizeof(ssl3_record_st) == 24, sizeof(ssl3_record_st)
|
| 1469 |
+
assert alignment(ssl3_record_st) == 4, alignment(ssl3_record_st)
|
| 1470 |
+
SSL3_RECORD = ssl3_record_st
|
| 1471 |
+
class ssl3_buffer_st(Structure):
|
| 1472 |
+
pass
|
| 1473 |
+
size_t = __darwin_size_t
|
| 1474 |
+
ssl3_buffer_st._fields_ = [
|
| 1475 |
+
('buf', POINTER(c_ubyte)),
|
| 1476 |
+
('len', size_t),
|
| 1477 |
+
('offset', c_int),
|
| 1478 |
+
('left', c_int),
|
| 1479 |
+
]
|
| 1480 |
+
assert sizeof(ssl3_buffer_st) == 16, sizeof(ssl3_buffer_st)
|
| 1481 |
+
assert alignment(ssl3_buffer_st) == 4, alignment(ssl3_buffer_st)
|
| 1482 |
+
SSL3_BUFFER = ssl3_buffer_st
|
| 1483 |
+
class N13ssl3_state_st4DOLLAR_20E(Structure):
|
| 1484 |
+
pass
|
| 1485 |
+
N13ssl3_state_st4DOLLAR_20E._fields_ = [
|
| 1486 |
+
('cert_verify_md', c_ubyte * 72),
|
| 1487 |
+
('finish_md', c_ubyte * 72),
|
| 1488 |
+
('finish_md_len', c_int),
|
| 1489 |
+
('peer_finish_md', c_ubyte * 72),
|
| 1490 |
+
('peer_finish_md_len', c_int),
|
| 1491 |
+
('message_size', c_ulong),
|
| 1492 |
+
('message_type', c_int),
|
| 1493 |
+
('new_cipher', POINTER(SSL_CIPHER)),
|
| 1494 |
+
('dh', POINTER(DH)),
|
| 1495 |
+
('next_state', c_int),
|
| 1496 |
+
('reuse_message', c_int),
|
| 1497 |
+
('cert_req', c_int),
|
| 1498 |
+
('ctype_num', c_int),
|
| 1499 |
+
('ctype', c_char * 7),
|
| 1500 |
+
('ca_names', POINTER(STACK)),
|
| 1501 |
+
('use_rsa_tmp', c_int),
|
| 1502 |
+
('key_block_length', c_int),
|
| 1503 |
+
('key_block', POINTER(c_ubyte)),
|
| 1504 |
+
('new_sym_enc', POINTER(EVP_CIPHER)),
|
| 1505 |
+
('new_hash', POINTER(EVP_MD)),
|
| 1506 |
+
('new_compression', POINTER(SSL_COMP)),
|
| 1507 |
+
('cert_request', c_int),
|
| 1508 |
+
]
|
| 1509 |
+
assert sizeof(N13ssl3_state_st4DOLLAR_20E) == 296, sizeof(N13ssl3_state_st4DOLLAR_20E)
|
| 1510 |
+
assert alignment(N13ssl3_state_st4DOLLAR_20E) == 4, alignment(N13ssl3_state_st4DOLLAR_20E)
|
| 1511 |
+
ssl3_state_st._fields_ = [
|
| 1512 |
+
('flags', c_long),
|
| 1513 |
+
('delay_buf_pop_ret', c_int),
|
| 1514 |
+
('read_sequence', c_ubyte * 8),
|
| 1515 |
+
('read_mac_secret', c_ubyte * 36),
|
| 1516 |
+
('write_sequence', c_ubyte * 8),
|
| 1517 |
+
('write_mac_secret', c_ubyte * 36),
|
| 1518 |
+
('server_random', c_ubyte * 32),
|
| 1519 |
+
('client_random', c_ubyte * 32),
|
| 1520 |
+
('need_empty_fragments', c_int),
|
| 1521 |
+
('empty_fragment_done', c_int),
|
| 1522 |
+
('rbuf', SSL3_BUFFER),
|
| 1523 |
+
('wbuf', SSL3_BUFFER),
|
| 1524 |
+
('rrec', SSL3_RECORD),
|
| 1525 |
+
('wrec', SSL3_RECORD),
|
| 1526 |
+
('alert_fragment', c_ubyte * 2),
|
| 1527 |
+
('alert_fragment_len', c_uint),
|
| 1528 |
+
('handshake_fragment', c_ubyte * 4),
|
| 1529 |
+
('handshake_fragment_len', c_uint),
|
| 1530 |
+
('wnum', c_uint),
|
| 1531 |
+
('wpend_tot', c_int),
|
| 1532 |
+
('wpend_type', c_int),
|
| 1533 |
+
('wpend_ret', c_int),
|
| 1534 |
+
('wpend_buf', POINTER(c_ubyte)),
|
| 1535 |
+
('finish_dgst1', EVP_MD_CTX),
|
| 1536 |
+
('finish_dgst2', EVP_MD_CTX),
|
| 1537 |
+
('change_cipher_spec', c_int),
|
| 1538 |
+
('warn_alert', c_int),
|
| 1539 |
+
('fatal_alert', c_int),
|
| 1540 |
+
('alert_dispatch', c_int),
|
| 1541 |
+
('send_alert', c_ubyte * 2),
|
| 1542 |
+
('renegotiate', c_int),
|
| 1543 |
+
('total_renegotiations', c_int),
|
| 1544 |
+
('num_renegotiations', c_int),
|
| 1545 |
+
('in_read_app_data', c_int),
|
| 1546 |
+
('tmp', N13ssl3_state_st4DOLLAR_20E),
|
| 1547 |
+
]
|
| 1548 |
+
assert sizeof(ssl3_state_st) == 648, sizeof(ssl3_state_st)
|
| 1549 |
+
assert alignment(ssl3_state_st) == 4, alignment(ssl3_state_st)
|
| 1550 |
+
SSL3_STATE = ssl3_state_st
|
| 1551 |
+
stack_st._fields_ = [
|
| 1552 |
+
('num', c_int),
|
| 1553 |
+
('data', POINTER(STRING)),
|
| 1554 |
+
('sorted', c_int),
|
| 1555 |
+
('num_alloc', c_int),
|
| 1556 |
+
('comp', CFUNCTYPE(c_int, POINTER(STRING), POINTER(STRING))),
|
| 1557 |
+
]
|
| 1558 |
+
assert sizeof(stack_st) == 20, sizeof(stack_st)
|
| 1559 |
+
assert alignment(stack_st) == 4, alignment(stack_st)
|
| 1560 |
+
class ui_st(Structure):
|
| 1561 |
+
pass
|
| 1562 |
+
ui_st._fields_ = [
|
| 1563 |
+
]
|
| 1564 |
+
UI = ui_st
|
| 1565 |
+
class ui_method_st(Structure):
|
| 1566 |
+
pass
|
| 1567 |
+
ui_method_st._fields_ = [
|
| 1568 |
+
]
|
| 1569 |
+
UI_METHOD = ui_method_st
|
| 1570 |
+
class ui_string_st(Structure):
|
| 1571 |
+
pass
|
| 1572 |
+
ui_string_st._fields_ = [
|
| 1573 |
+
]
|
| 1574 |
+
UI_STRING = ui_string_st
|
| 1575 |
+
|
| 1576 |
+
# values for enumeration 'UI_string_types'
|
| 1577 |
+
UI_string_types = c_int # enum
|
| 1578 |
+
class X509_objects_st(Structure):
|
| 1579 |
+
pass
|
| 1580 |
+
X509_objects_st._fields_ = [
|
| 1581 |
+
('nid', c_int),
|
| 1582 |
+
('a2i', CFUNCTYPE(c_int)),
|
| 1583 |
+
('i2a', CFUNCTYPE(c_int)),
|
| 1584 |
+
]
|
| 1585 |
+
assert sizeof(X509_objects_st) == 12, sizeof(X509_objects_st)
|
| 1586 |
+
assert alignment(X509_objects_st) == 4, alignment(X509_objects_st)
|
| 1587 |
+
X509_OBJECTS = X509_objects_st
|
| 1588 |
+
X509_algor_st._fields_ = [
|
| 1589 |
+
('algorithm', POINTER(ASN1_OBJECT)),
|
| 1590 |
+
('parameter', POINTER(ASN1_TYPE)),
|
| 1591 |
+
]
|
| 1592 |
+
assert sizeof(X509_algor_st) == 8, sizeof(X509_algor_st)
|
| 1593 |
+
assert alignment(X509_algor_st) == 4, alignment(X509_algor_st)
|
| 1594 |
+
class X509_val_st(Structure):
|
| 1595 |
+
pass
|
| 1596 |
+
X509_val_st._fields_ = [
|
| 1597 |
+
('notBefore', POINTER(ASN1_TIME)),
|
| 1598 |
+
('notAfter', POINTER(ASN1_TIME)),
|
| 1599 |
+
]
|
| 1600 |
+
assert sizeof(X509_val_st) == 8, sizeof(X509_val_st)
|
| 1601 |
+
assert alignment(X509_val_st) == 4, alignment(X509_val_st)
|
| 1602 |
+
X509_VAL = X509_val_st
|
| 1603 |
+
class X509_pubkey_st(Structure):
|
| 1604 |
+
pass
|
| 1605 |
+
X509_pubkey_st._fields_ = [
|
| 1606 |
+
('algor', POINTER(X509_ALGOR)),
|
| 1607 |
+
('public_key', POINTER(ASN1_BIT_STRING)),
|
| 1608 |
+
('pkey', POINTER(EVP_PKEY)),
|
| 1609 |
+
]
|
| 1610 |
+
assert sizeof(X509_pubkey_st) == 12, sizeof(X509_pubkey_st)
|
| 1611 |
+
assert alignment(X509_pubkey_st) == 4, alignment(X509_pubkey_st)
|
| 1612 |
+
X509_PUBKEY = X509_pubkey_st
|
| 1613 |
+
class X509_sig_st(Structure):
|
| 1614 |
+
pass
|
| 1615 |
+
X509_sig_st._fields_ = [
|
| 1616 |
+
('algor', POINTER(X509_ALGOR)),
|
| 1617 |
+
('digest', POINTER(ASN1_OCTET_STRING)),
|
| 1618 |
+
]
|
| 1619 |
+
assert sizeof(X509_sig_st) == 8, sizeof(X509_sig_st)
|
| 1620 |
+
assert alignment(X509_sig_st) == 4, alignment(X509_sig_st)
|
| 1621 |
+
X509_SIG = X509_sig_st
|
| 1622 |
+
class X509_name_entry_st(Structure):
|
| 1623 |
+
pass
|
| 1624 |
+
X509_name_entry_st._fields_ = [
|
| 1625 |
+
('object', POINTER(ASN1_OBJECT)),
|
| 1626 |
+
('value', POINTER(ASN1_STRING)),
|
| 1627 |
+
('set', c_int),
|
| 1628 |
+
('size', c_int),
|
| 1629 |
+
]
|
| 1630 |
+
assert sizeof(X509_name_entry_st) == 16, sizeof(X509_name_entry_st)
|
| 1631 |
+
assert alignment(X509_name_entry_st) == 4, alignment(X509_name_entry_st)
|
| 1632 |
+
X509_NAME_ENTRY = X509_name_entry_st
|
| 1633 |
+
X509_name_st._fields_ = [
|
| 1634 |
+
('entries', POINTER(STACK)),
|
| 1635 |
+
('modified', c_int),
|
| 1636 |
+
('bytes', POINTER(BUF_MEM)),
|
| 1637 |
+
('hash', c_ulong),
|
| 1638 |
+
]
|
| 1639 |
+
assert sizeof(X509_name_st) == 16, sizeof(X509_name_st)
|
| 1640 |
+
assert alignment(X509_name_st) == 4, alignment(X509_name_st)
|
| 1641 |
+
class X509_extension_st(Structure):
|
| 1642 |
+
pass
|
| 1643 |
+
X509_extension_st._fields_ = [
|
| 1644 |
+
('object', POINTER(ASN1_OBJECT)),
|
| 1645 |
+
('critical', ASN1_BOOLEAN),
|
| 1646 |
+
('value', POINTER(ASN1_OCTET_STRING)),
|
| 1647 |
+
]
|
| 1648 |
+
assert sizeof(X509_extension_st) == 12, sizeof(X509_extension_st)
|
| 1649 |
+
assert alignment(X509_extension_st) == 4, alignment(X509_extension_st)
|
| 1650 |
+
X509_EXTENSION = X509_extension_st
|
| 1651 |
+
class x509_attributes_st(Structure):
|
| 1652 |
+
pass
|
| 1653 |
+
class N18x509_attributes_st4DOLLAR_13E(Union):
|
| 1654 |
+
pass
|
| 1655 |
+
N18x509_attributes_st4DOLLAR_13E._fields_ = [
|
| 1656 |
+
('ptr', STRING),
|
| 1657 |
+
('set', POINTER(STACK)),
|
| 1658 |
+
('single', POINTER(ASN1_TYPE)),
|
| 1659 |
+
]
|
| 1660 |
+
assert sizeof(N18x509_attributes_st4DOLLAR_13E) == 4, sizeof(N18x509_attributes_st4DOLLAR_13E)
|
| 1661 |
+
assert alignment(N18x509_attributes_st4DOLLAR_13E) == 4, alignment(N18x509_attributes_st4DOLLAR_13E)
|
| 1662 |
+
x509_attributes_st._fields_ = [
|
| 1663 |
+
('object', POINTER(ASN1_OBJECT)),
|
| 1664 |
+
('single', c_int),
|
| 1665 |
+
('value', N18x509_attributes_st4DOLLAR_13E),
|
| 1666 |
+
]
|
| 1667 |
+
assert sizeof(x509_attributes_st) == 12, sizeof(x509_attributes_st)
|
| 1668 |
+
assert alignment(x509_attributes_st) == 4, alignment(x509_attributes_st)
|
| 1669 |
+
X509_ATTRIBUTE = x509_attributes_st
|
| 1670 |
+
class X509_req_info_st(Structure):
|
| 1671 |
+
pass
|
| 1672 |
+
X509_req_info_st._fields_ = [
|
| 1673 |
+
('enc', ASN1_ENCODING),
|
| 1674 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1675 |
+
('subject', POINTER(X509_NAME)),
|
| 1676 |
+
('pubkey', POINTER(X509_PUBKEY)),
|
| 1677 |
+
('attributes', POINTER(STACK)),
|
| 1678 |
+
]
|
| 1679 |
+
assert sizeof(X509_req_info_st) == 28, sizeof(X509_req_info_st)
|
| 1680 |
+
assert alignment(X509_req_info_st) == 4, alignment(X509_req_info_st)
|
| 1681 |
+
X509_REQ_INFO = X509_req_info_st
|
| 1682 |
+
class X509_req_st(Structure):
|
| 1683 |
+
pass
|
| 1684 |
+
X509_req_st._fields_ = [
|
| 1685 |
+
('req_info', POINTER(X509_REQ_INFO)),
|
| 1686 |
+
('sig_alg', POINTER(X509_ALGOR)),
|
| 1687 |
+
('signature', POINTER(ASN1_BIT_STRING)),
|
| 1688 |
+
('references', c_int),
|
| 1689 |
+
]
|
| 1690 |
+
assert sizeof(X509_req_st) == 16, sizeof(X509_req_st)
|
| 1691 |
+
assert alignment(X509_req_st) == 4, alignment(X509_req_st)
|
| 1692 |
+
X509_REQ = X509_req_st
|
| 1693 |
+
class x509_cinf_st(Structure):
|
| 1694 |
+
pass
|
| 1695 |
+
x509_cinf_st._fields_ = [
|
| 1696 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1697 |
+
('serialNumber', POINTER(ASN1_INTEGER)),
|
| 1698 |
+
('signature', POINTER(X509_ALGOR)),
|
| 1699 |
+
('issuer', POINTER(X509_NAME)),
|
| 1700 |
+
('validity', POINTER(X509_VAL)),
|
| 1701 |
+
('subject', POINTER(X509_NAME)),
|
| 1702 |
+
('key', POINTER(X509_PUBKEY)),
|
| 1703 |
+
('issuerUID', POINTER(ASN1_BIT_STRING)),
|
| 1704 |
+
('subjectUID', POINTER(ASN1_BIT_STRING)),
|
| 1705 |
+
('extensions', POINTER(STACK)),
|
| 1706 |
+
]
|
| 1707 |
+
assert sizeof(x509_cinf_st) == 40, sizeof(x509_cinf_st)
|
| 1708 |
+
assert alignment(x509_cinf_st) == 4, alignment(x509_cinf_st)
|
| 1709 |
+
X509_CINF = x509_cinf_st
|
| 1710 |
+
class x509_cert_aux_st(Structure):
|
| 1711 |
+
pass
|
| 1712 |
+
x509_cert_aux_st._fields_ = [
|
| 1713 |
+
('trust', POINTER(STACK)),
|
| 1714 |
+
('reject', POINTER(STACK)),
|
| 1715 |
+
('alias', POINTER(ASN1_UTF8STRING)),
|
| 1716 |
+
('keyid', POINTER(ASN1_OCTET_STRING)),
|
| 1717 |
+
('other', POINTER(STACK)),
|
| 1718 |
+
]
|
| 1719 |
+
assert sizeof(x509_cert_aux_st) == 20, sizeof(x509_cert_aux_st)
|
| 1720 |
+
assert alignment(x509_cert_aux_st) == 4, alignment(x509_cert_aux_st)
|
| 1721 |
+
X509_CERT_AUX = x509_cert_aux_st
|
| 1722 |
+
class AUTHORITY_KEYID_st(Structure):
|
| 1723 |
+
pass
|
| 1724 |
+
x509_st._fields_ = [
|
| 1725 |
+
('cert_info', POINTER(X509_CINF)),
|
| 1726 |
+
('sig_alg', POINTER(X509_ALGOR)),
|
| 1727 |
+
('signature', POINTER(ASN1_BIT_STRING)),
|
| 1728 |
+
('valid', c_int),
|
| 1729 |
+
('references', c_int),
|
| 1730 |
+
('name', STRING),
|
| 1731 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 1732 |
+
('ex_pathlen', c_long),
|
| 1733 |
+
('ex_flags', c_ulong),
|
| 1734 |
+
('ex_kusage', c_ulong),
|
| 1735 |
+
('ex_xkusage', c_ulong),
|
| 1736 |
+
('ex_nscert', c_ulong),
|
| 1737 |
+
('skid', POINTER(ASN1_OCTET_STRING)),
|
| 1738 |
+
('akid', POINTER(AUTHORITY_KEYID_st)),
|
| 1739 |
+
('sha1_hash', c_ubyte * 20),
|
| 1740 |
+
('aux', POINTER(X509_CERT_AUX)),
|
| 1741 |
+
]
|
| 1742 |
+
assert sizeof(x509_st) == 84, sizeof(x509_st)
|
| 1743 |
+
assert alignment(x509_st) == 4, alignment(x509_st)
|
| 1744 |
+
AUTHORITY_KEYID_st._fields_ = [
|
| 1745 |
+
]
|
| 1746 |
+
class x509_trust_st(Structure):
|
| 1747 |
+
pass
|
| 1748 |
+
x509_trust_st._fields_ = [
|
| 1749 |
+
('trust', c_int),
|
| 1750 |
+
('flags', c_int),
|
| 1751 |
+
('check_trust', CFUNCTYPE(c_int, POINTER(x509_trust_st), POINTER(X509), c_int)),
|
| 1752 |
+
('name', STRING),
|
| 1753 |
+
('arg1', c_int),
|
| 1754 |
+
('arg2', c_void_p),
|
| 1755 |
+
]
|
| 1756 |
+
assert sizeof(x509_trust_st) == 24, sizeof(x509_trust_st)
|
| 1757 |
+
assert alignment(x509_trust_st) == 4, alignment(x509_trust_st)
|
| 1758 |
+
X509_TRUST = x509_trust_st
|
| 1759 |
+
class X509_revoked_st(Structure):
|
| 1760 |
+
pass
|
| 1761 |
+
X509_revoked_st._fields_ = [
|
| 1762 |
+
('serialNumber', POINTER(ASN1_INTEGER)),
|
| 1763 |
+
('revocationDate', POINTER(ASN1_TIME)),
|
| 1764 |
+
('extensions', POINTER(STACK)),
|
| 1765 |
+
('sequence', c_int),
|
| 1766 |
+
]
|
| 1767 |
+
assert sizeof(X509_revoked_st) == 16, sizeof(X509_revoked_st)
|
| 1768 |
+
assert alignment(X509_revoked_st) == 4, alignment(X509_revoked_st)
|
| 1769 |
+
X509_REVOKED = X509_revoked_st
|
| 1770 |
+
class X509_crl_info_st(Structure):
|
| 1771 |
+
pass
|
| 1772 |
+
X509_crl_info_st._fields_ = [
|
| 1773 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1774 |
+
('sig_alg', POINTER(X509_ALGOR)),
|
| 1775 |
+
('issuer', POINTER(X509_NAME)),
|
| 1776 |
+
('lastUpdate', POINTER(ASN1_TIME)),
|
| 1777 |
+
('nextUpdate', POINTER(ASN1_TIME)),
|
| 1778 |
+
('revoked', POINTER(STACK)),
|
| 1779 |
+
('extensions', POINTER(STACK)),
|
| 1780 |
+
('enc', ASN1_ENCODING),
|
| 1781 |
+
]
|
| 1782 |
+
assert sizeof(X509_crl_info_st) == 40, sizeof(X509_crl_info_st)
|
| 1783 |
+
assert alignment(X509_crl_info_st) == 4, alignment(X509_crl_info_st)
|
| 1784 |
+
X509_CRL_INFO = X509_crl_info_st
|
| 1785 |
+
X509_crl_st._fields_ = [
|
| 1786 |
+
('crl', POINTER(X509_CRL_INFO)),
|
| 1787 |
+
('sig_alg', POINTER(X509_ALGOR)),
|
| 1788 |
+
('signature', POINTER(ASN1_BIT_STRING)),
|
| 1789 |
+
('references', c_int),
|
| 1790 |
+
]
|
| 1791 |
+
assert sizeof(X509_crl_st) == 16, sizeof(X509_crl_st)
|
| 1792 |
+
assert alignment(X509_crl_st) == 4, alignment(X509_crl_st)
|
| 1793 |
+
class private_key_st(Structure):
|
| 1794 |
+
pass
|
| 1795 |
+
private_key_st._fields_ = [
|
| 1796 |
+
('version', c_int),
|
| 1797 |
+
('enc_algor', POINTER(X509_ALGOR)),
|
| 1798 |
+
('enc_pkey', POINTER(ASN1_OCTET_STRING)),
|
| 1799 |
+
('dec_pkey', POINTER(EVP_PKEY)),
|
| 1800 |
+
('key_length', c_int),
|
| 1801 |
+
('key_data', STRING),
|
| 1802 |
+
('key_free', c_int),
|
| 1803 |
+
('cipher', EVP_CIPHER_INFO),
|
| 1804 |
+
('references', c_int),
|
| 1805 |
+
]
|
| 1806 |
+
assert sizeof(private_key_st) == 52, sizeof(private_key_st)
|
| 1807 |
+
assert alignment(private_key_st) == 4, alignment(private_key_st)
|
| 1808 |
+
X509_PKEY = private_key_st
|
| 1809 |
+
class X509_info_st(Structure):
|
| 1810 |
+
pass
|
| 1811 |
+
X509_info_st._fields_ = [
|
| 1812 |
+
('x509', POINTER(X509)),
|
| 1813 |
+
('crl', POINTER(X509_CRL)),
|
| 1814 |
+
('x_pkey', POINTER(X509_PKEY)),
|
| 1815 |
+
('enc_cipher', EVP_CIPHER_INFO),
|
| 1816 |
+
('enc_len', c_int),
|
| 1817 |
+
('enc_data', STRING),
|
| 1818 |
+
('references', c_int),
|
| 1819 |
+
]
|
| 1820 |
+
assert sizeof(X509_info_st) == 44, sizeof(X509_info_st)
|
| 1821 |
+
assert alignment(X509_info_st) == 4, alignment(X509_info_st)
|
| 1822 |
+
X509_INFO = X509_info_st
|
| 1823 |
+
class Netscape_spkac_st(Structure):
|
| 1824 |
+
pass
|
| 1825 |
+
Netscape_spkac_st._fields_ = [
|
| 1826 |
+
('pubkey', POINTER(X509_PUBKEY)),
|
| 1827 |
+
('challenge', POINTER(ASN1_IA5STRING)),
|
| 1828 |
+
]
|
| 1829 |
+
assert sizeof(Netscape_spkac_st) == 8, sizeof(Netscape_spkac_st)
|
| 1830 |
+
assert alignment(Netscape_spkac_st) == 4, alignment(Netscape_spkac_st)
|
| 1831 |
+
NETSCAPE_SPKAC = Netscape_spkac_st
|
| 1832 |
+
class Netscape_spki_st(Structure):
|
| 1833 |
+
pass
|
| 1834 |
+
Netscape_spki_st._fields_ = [
|
| 1835 |
+
('spkac', POINTER(NETSCAPE_SPKAC)),
|
| 1836 |
+
('sig_algor', POINTER(X509_ALGOR)),
|
| 1837 |
+
('signature', POINTER(ASN1_BIT_STRING)),
|
| 1838 |
+
]
|
| 1839 |
+
assert sizeof(Netscape_spki_st) == 12, sizeof(Netscape_spki_st)
|
| 1840 |
+
assert alignment(Netscape_spki_st) == 4, alignment(Netscape_spki_st)
|
| 1841 |
+
NETSCAPE_SPKI = Netscape_spki_st
|
| 1842 |
+
class Netscape_certificate_sequence(Structure):
|
| 1843 |
+
pass
|
| 1844 |
+
Netscape_certificate_sequence._fields_ = [
|
| 1845 |
+
('type', POINTER(ASN1_OBJECT)),
|
| 1846 |
+
('certs', POINTER(STACK)),
|
| 1847 |
+
]
|
| 1848 |
+
assert sizeof(Netscape_certificate_sequence) == 8, sizeof(Netscape_certificate_sequence)
|
| 1849 |
+
assert alignment(Netscape_certificate_sequence) == 4, alignment(Netscape_certificate_sequence)
|
| 1850 |
+
NETSCAPE_CERT_SEQUENCE = Netscape_certificate_sequence
|
| 1851 |
+
class PBEPARAM_st(Structure):
|
| 1852 |
+
pass
|
| 1853 |
+
PBEPARAM_st._fields_ = [
|
| 1854 |
+
('salt', POINTER(ASN1_OCTET_STRING)),
|
| 1855 |
+
('iter', POINTER(ASN1_INTEGER)),
|
| 1856 |
+
]
|
| 1857 |
+
assert sizeof(PBEPARAM_st) == 8, sizeof(PBEPARAM_st)
|
| 1858 |
+
assert alignment(PBEPARAM_st) == 4, alignment(PBEPARAM_st)
|
| 1859 |
+
PBEPARAM = PBEPARAM_st
|
| 1860 |
+
class PBE2PARAM_st(Structure):
|
| 1861 |
+
pass
|
| 1862 |
+
PBE2PARAM_st._fields_ = [
|
| 1863 |
+
('keyfunc', POINTER(X509_ALGOR)),
|
| 1864 |
+
('encryption', POINTER(X509_ALGOR)),
|
| 1865 |
+
]
|
| 1866 |
+
assert sizeof(PBE2PARAM_st) == 8, sizeof(PBE2PARAM_st)
|
| 1867 |
+
assert alignment(PBE2PARAM_st) == 4, alignment(PBE2PARAM_st)
|
| 1868 |
+
PBE2PARAM = PBE2PARAM_st
|
| 1869 |
+
class PBKDF2PARAM_st(Structure):
|
| 1870 |
+
pass
|
| 1871 |
+
PBKDF2PARAM_st._fields_ = [
|
| 1872 |
+
('salt', POINTER(ASN1_TYPE)),
|
| 1873 |
+
('iter', POINTER(ASN1_INTEGER)),
|
| 1874 |
+
('keylength', POINTER(ASN1_INTEGER)),
|
| 1875 |
+
('prf', POINTER(X509_ALGOR)),
|
| 1876 |
+
]
|
| 1877 |
+
assert sizeof(PBKDF2PARAM_st) == 16, sizeof(PBKDF2PARAM_st)
|
| 1878 |
+
assert alignment(PBKDF2PARAM_st) == 4, alignment(PBKDF2PARAM_st)
|
| 1879 |
+
PBKDF2PARAM = PBKDF2PARAM_st
|
| 1880 |
+
class pkcs8_priv_key_info_st(Structure):
|
| 1881 |
+
pass
|
| 1882 |
+
pkcs8_priv_key_info_st._fields_ = [
|
| 1883 |
+
('broken', c_int),
|
| 1884 |
+
('version', POINTER(ASN1_INTEGER)),
|
| 1885 |
+
('pkeyalg', POINTER(X509_ALGOR)),
|
| 1886 |
+
('pkey', POINTER(ASN1_TYPE)),
|
| 1887 |
+
('attributes', POINTER(STACK)),
|
| 1888 |
+
]
|
| 1889 |
+
assert sizeof(pkcs8_priv_key_info_st) == 20, sizeof(pkcs8_priv_key_info_st)
|
| 1890 |
+
assert alignment(pkcs8_priv_key_info_st) == 4, alignment(pkcs8_priv_key_info_st)
|
| 1891 |
+
PKCS8_PRIV_KEY_INFO = pkcs8_priv_key_info_st
|
| 1892 |
+
class x509_hash_dir_st(Structure):
|
| 1893 |
+
pass
|
| 1894 |
+
x509_hash_dir_st._fields_ = [
|
| 1895 |
+
('num_dirs', c_int),
|
| 1896 |
+
('dirs', POINTER(STRING)),
|
| 1897 |
+
('dirs_type', POINTER(c_int)),
|
| 1898 |
+
('num_dirs_alloced', c_int),
|
| 1899 |
+
]
|
| 1900 |
+
assert sizeof(x509_hash_dir_st) == 16, sizeof(x509_hash_dir_st)
|
| 1901 |
+
assert alignment(x509_hash_dir_st) == 4, alignment(x509_hash_dir_st)
|
| 1902 |
+
X509_HASH_DIR_CTX = x509_hash_dir_st
|
| 1903 |
+
class x509_file_st(Structure):
|
| 1904 |
+
pass
|
| 1905 |
+
x509_file_st._fields_ = [
|
| 1906 |
+
('num_paths', c_int),
|
| 1907 |
+
('num_alloced', c_int),
|
| 1908 |
+
('paths', POINTER(STRING)),
|
| 1909 |
+
('path_type', POINTER(c_int)),
|
| 1910 |
+
]
|
| 1911 |
+
assert sizeof(x509_file_st) == 16, sizeof(x509_file_st)
|
| 1912 |
+
assert alignment(x509_file_st) == 4, alignment(x509_file_st)
|
| 1913 |
+
X509_CERT_FILE_CTX = x509_file_st
|
| 1914 |
+
class x509_object_st(Structure):
|
| 1915 |
+
pass
|
| 1916 |
+
class N14x509_object_st4DOLLAR_14E(Union):
|
| 1917 |
+
pass
|
| 1918 |
+
N14x509_object_st4DOLLAR_14E._fields_ = [
|
| 1919 |
+
('ptr', STRING),
|
| 1920 |
+
('x509', POINTER(X509)),
|
| 1921 |
+
('crl', POINTER(X509_CRL)),
|
| 1922 |
+
('pkey', POINTER(EVP_PKEY)),
|
| 1923 |
+
]
|
| 1924 |
+
assert sizeof(N14x509_object_st4DOLLAR_14E) == 4, sizeof(N14x509_object_st4DOLLAR_14E)
|
| 1925 |
+
assert alignment(N14x509_object_st4DOLLAR_14E) == 4, alignment(N14x509_object_st4DOLLAR_14E)
|
| 1926 |
+
x509_object_st._fields_ = [
|
| 1927 |
+
('type', c_int),
|
| 1928 |
+
('data', N14x509_object_st4DOLLAR_14E),
|
| 1929 |
+
]
|
| 1930 |
+
assert sizeof(x509_object_st) == 8, sizeof(x509_object_st)
|
| 1931 |
+
assert alignment(x509_object_st) == 4, alignment(x509_object_st)
|
| 1932 |
+
X509_OBJECT = x509_object_st
|
| 1933 |
+
class x509_lookup_st(Structure):
|
| 1934 |
+
pass
|
| 1935 |
+
X509_LOOKUP = x509_lookup_st
|
| 1936 |
+
class x509_lookup_method_st(Structure):
|
| 1937 |
+
pass
|
| 1938 |
+
x509_lookup_method_st._fields_ = [
|
| 1939 |
+
('name', STRING),
|
| 1940 |
+
('new_item', CFUNCTYPE(c_int, POINTER(X509_LOOKUP))),
|
| 1941 |
+
('free', CFUNCTYPE(None, POINTER(X509_LOOKUP))),
|
| 1942 |
+
('init', CFUNCTYPE(c_int, POINTER(X509_LOOKUP))),
|
| 1943 |
+
('shutdown', CFUNCTYPE(c_int, POINTER(X509_LOOKUP))),
|
| 1944 |
+
('ctrl', CFUNCTYPE(c_int, POINTER(X509_LOOKUP), c_int, STRING, c_long, POINTER(STRING))),
|
| 1945 |
+
('get_by_subject', CFUNCTYPE(c_int, POINTER(X509_LOOKUP), c_int, POINTER(X509_NAME), POINTER(X509_OBJECT))),
|
| 1946 |
+
('get_by_issuer_serial', CFUNCTYPE(c_int, POINTER(X509_LOOKUP), c_int, POINTER(X509_NAME), POINTER(ASN1_INTEGER), POINTER(X509_OBJECT))),
|
| 1947 |
+
('get_by_fingerprint', CFUNCTYPE(c_int, POINTER(X509_LOOKUP), c_int, POINTER(c_ubyte), c_int, POINTER(X509_OBJECT))),
|
| 1948 |
+
('get_by_alias', CFUNCTYPE(c_int, POINTER(X509_LOOKUP), c_int, STRING, c_int, POINTER(X509_OBJECT))),
|
| 1949 |
+
]
|
| 1950 |
+
assert sizeof(x509_lookup_method_st) == 40, sizeof(x509_lookup_method_st)
|
| 1951 |
+
assert alignment(x509_lookup_method_st) == 4, alignment(x509_lookup_method_st)
|
| 1952 |
+
X509_LOOKUP_METHOD = x509_lookup_method_st
|
| 1953 |
+
x509_store_st._fields_ = [
|
| 1954 |
+
('cache', c_int),
|
| 1955 |
+
('objs', POINTER(STACK)),
|
| 1956 |
+
('get_cert_methods', POINTER(STACK)),
|
| 1957 |
+
('flags', c_ulong),
|
| 1958 |
+
('purpose', c_int),
|
| 1959 |
+
('trust', c_int),
|
| 1960 |
+
('verify', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX))),
|
| 1961 |
+
('verify_cb', CFUNCTYPE(c_int, c_int, POINTER(X509_STORE_CTX))),
|
| 1962 |
+
('get_issuer', CFUNCTYPE(c_int, POINTER(POINTER(X509)), POINTER(X509_STORE_CTX), POINTER(X509))),
|
| 1963 |
+
('check_issued', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(X509), POINTER(X509))),
|
| 1964 |
+
('check_revocation', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX))),
|
| 1965 |
+
('get_crl', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(POINTER(X509_CRL)), POINTER(X509))),
|
| 1966 |
+
('check_crl', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(X509_CRL))),
|
| 1967 |
+
('cert_crl', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(X509_CRL), POINTER(X509))),
|
| 1968 |
+
('cleanup', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX))),
|
| 1969 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 1970 |
+
('references', c_int),
|
| 1971 |
+
('depth', c_int),
|
| 1972 |
+
]
|
| 1973 |
+
assert sizeof(x509_store_st) == 76, sizeof(x509_store_st)
|
| 1974 |
+
assert alignment(x509_store_st) == 4, alignment(x509_store_st)
|
| 1975 |
+
x509_lookup_st._fields_ = [
|
| 1976 |
+
('init', c_int),
|
| 1977 |
+
('skip', c_int),
|
| 1978 |
+
('method', POINTER(X509_LOOKUP_METHOD)),
|
| 1979 |
+
('method_data', STRING),
|
| 1980 |
+
('store_ctx', POINTER(X509_STORE)),
|
| 1981 |
+
]
|
| 1982 |
+
assert sizeof(x509_lookup_st) == 20, sizeof(x509_lookup_st)
|
| 1983 |
+
assert alignment(x509_lookup_st) == 4, alignment(x509_lookup_st)
|
| 1984 |
+
time_t = __darwin_time_t
|
| 1985 |
+
x509_store_ctx_st._fields_ = [
|
| 1986 |
+
('ctx', POINTER(X509_STORE)),
|
| 1987 |
+
('current_method', c_int),
|
| 1988 |
+
('cert', POINTER(X509)),
|
| 1989 |
+
('untrusted', POINTER(STACK)),
|
| 1990 |
+
('purpose', c_int),
|
| 1991 |
+
('trust', c_int),
|
| 1992 |
+
('check_time', time_t),
|
| 1993 |
+
('flags', c_ulong),
|
| 1994 |
+
('other_ctx', c_void_p),
|
| 1995 |
+
('verify', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX))),
|
| 1996 |
+
('verify_cb', CFUNCTYPE(c_int, c_int, POINTER(X509_STORE_CTX))),
|
| 1997 |
+
('get_issuer', CFUNCTYPE(c_int, POINTER(POINTER(X509)), POINTER(X509_STORE_CTX), POINTER(X509))),
|
| 1998 |
+
('check_issued', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(X509), POINTER(X509))),
|
| 1999 |
+
('check_revocation', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX))),
|
| 2000 |
+
('get_crl', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(POINTER(X509_CRL)), POINTER(X509))),
|
| 2001 |
+
('check_crl', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(X509_CRL))),
|
| 2002 |
+
('cert_crl', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX), POINTER(X509_CRL), POINTER(X509))),
|
| 2003 |
+
('cleanup', CFUNCTYPE(c_int, POINTER(X509_STORE_CTX))),
|
| 2004 |
+
('depth', c_int),
|
| 2005 |
+
('valid', c_int),
|
| 2006 |
+
('last_untrusted', c_int),
|
| 2007 |
+
('chain', POINTER(STACK)),
|
| 2008 |
+
('error_depth', c_int),
|
| 2009 |
+
('error', c_int),
|
| 2010 |
+
('current_cert', POINTER(X509)),
|
| 2011 |
+
('current_issuer', POINTER(X509)),
|
| 2012 |
+
('current_crl', POINTER(X509_CRL)),
|
| 2013 |
+
('ex_data', CRYPTO_EX_DATA),
|
| 2014 |
+
]
|
| 2015 |
+
assert sizeof(x509_store_ctx_st) == 116, sizeof(x509_store_ctx_st)
|
| 2016 |
+
assert alignment(x509_store_ctx_st) == 4, alignment(x509_store_ctx_st)
|
| 2017 |
+
va_list = __darwin_va_list
|
| 2018 |
+
__darwin_off_t = __int64_t
|
| 2019 |
+
fpos_t = __darwin_off_t
|
| 2020 |
+
class __sbuf(Structure):
|
| 2021 |
+
pass
|
| 2022 |
+
__sbuf._fields_ = [
|
| 2023 |
+
('_base', POINTER(c_ubyte)),
|
| 2024 |
+
('_size', c_int),
|
| 2025 |
+
]
|
| 2026 |
+
assert sizeof(__sbuf) == 8, sizeof(__sbuf)
|
| 2027 |
+
assert alignment(__sbuf) == 4, alignment(__sbuf)
|
| 2028 |
+
class __sFILEX(Structure):
|
| 2029 |
+
pass
|
| 2030 |
+
__sFILEX._fields_ = [
|
| 2031 |
+
]
|
| 2032 |
+
class __sFILE(Structure):
|
| 2033 |
+
pass
|
| 2034 |
+
__sFILE._pack_ = 4
|
| 2035 |
+
__sFILE._fields_ = [
|
| 2036 |
+
('_p', POINTER(c_ubyte)),
|
| 2037 |
+
('_r', c_int),
|
| 2038 |
+
('_w', c_int),
|
| 2039 |
+
('_flags', c_short),
|
| 2040 |
+
('_file', c_short),
|
| 2041 |
+
('_bf', __sbuf),
|
| 2042 |
+
('_lbfsize', c_int),
|
| 2043 |
+
('_cookie', c_void_p),
|
| 2044 |
+
('_close', CFUNCTYPE(c_int, c_void_p)),
|
| 2045 |
+
('_read', CFUNCTYPE(c_int, c_void_p, STRING, c_int)),
|
| 2046 |
+
('_seek', CFUNCTYPE(fpos_t, c_void_p, c_longlong, c_int)),
|
| 2047 |
+
('_write', CFUNCTYPE(c_int, c_void_p, STRING, c_int)),
|
| 2048 |
+
('_ub', __sbuf),
|
| 2049 |
+
('_extra', POINTER(__sFILEX)),
|
| 2050 |
+
('_ur', c_int),
|
| 2051 |
+
('_ubuf', c_ubyte * 3),
|
| 2052 |
+
('_nbuf', c_ubyte * 1),
|
| 2053 |
+
('_lb', __sbuf),
|
| 2054 |
+
('_blksize', c_int),
|
| 2055 |
+
('_offset', fpos_t),
|
| 2056 |
+
]
|
| 2057 |
+
assert sizeof(__sFILE) == 88, sizeof(__sFILE)
|
| 2058 |
+
assert alignment(__sFILE) == 4, alignment(__sFILE)
|
| 2059 |
+
FILE = __sFILE
|
| 2060 |
+
ct_rune_t = __darwin_ct_rune_t
|
| 2061 |
+
rune_t = __darwin_rune_t
|
| 2062 |
+
class div_t(Structure):
|
| 2063 |
+
pass
|
| 2064 |
+
div_t._fields_ = [
|
| 2065 |
+
('quot', c_int),
|
| 2066 |
+
('rem', c_int),
|
| 2067 |
+
]
|
| 2068 |
+
assert sizeof(div_t) == 8, sizeof(div_t)
|
| 2069 |
+
assert alignment(div_t) == 4, alignment(div_t)
|
| 2070 |
+
class ldiv_t(Structure):
|
| 2071 |
+
pass
|
| 2072 |
+
ldiv_t._fields_ = [
|
| 2073 |
+
('quot', c_long),
|
| 2074 |
+
('rem', c_long),
|
| 2075 |
+
]
|
| 2076 |
+
assert sizeof(ldiv_t) == 8, sizeof(ldiv_t)
|
| 2077 |
+
assert alignment(ldiv_t) == 4, alignment(ldiv_t)
|
| 2078 |
+
class lldiv_t(Structure):
|
| 2079 |
+
pass
|
| 2080 |
+
lldiv_t._pack_ = 4
|
| 2081 |
+
lldiv_t._fields_ = [
|
| 2082 |
+
('quot', c_longlong),
|
| 2083 |
+
('rem', c_longlong),
|
| 2084 |
+
]
|
| 2085 |
+
assert sizeof(lldiv_t) == 16, sizeof(lldiv_t)
|
| 2086 |
+
assert alignment(lldiv_t) == 4, alignment(lldiv_t)
|
| 2087 |
+
__darwin_dev_t = __int32_t
|
| 2088 |
+
dev_t = __darwin_dev_t
|
| 2089 |
+
__darwin_mode_t = __uint16_t
|
| 2090 |
+
mode_t = __darwin_mode_t
|
| 2091 |
+
class mcontext(Structure):
|
| 2092 |
+
pass
|
| 2093 |
+
mcontext._fields_ = [
|
| 2094 |
+
]
|
| 2095 |
+
class mcontext64(Structure):
|
| 2096 |
+
pass
|
| 2097 |
+
mcontext64._fields_ = [
|
| 2098 |
+
]
|
| 2099 |
+
class __darwin_pthread_handler_rec(Structure):
|
| 2100 |
+
pass
|
| 2101 |
+
__darwin_pthread_handler_rec._fields_ = [
|
| 2102 |
+
('__routine', CFUNCTYPE(None, c_void_p)),
|
| 2103 |
+
('__arg', c_void_p),
|
| 2104 |
+
('__next', POINTER(__darwin_pthread_handler_rec)),
|
| 2105 |
+
]
|
| 2106 |
+
assert sizeof(__darwin_pthread_handler_rec) == 12, sizeof(__darwin_pthread_handler_rec)
|
| 2107 |
+
assert alignment(__darwin_pthread_handler_rec) == 4, alignment(__darwin_pthread_handler_rec)
|
| 2108 |
+
class _opaque_pthread_attr_t(Structure):
|
| 2109 |
+
pass
|
| 2110 |
+
_opaque_pthread_attr_t._fields_ = [
|
| 2111 |
+
('__sig', c_long),
|
| 2112 |
+
('__opaque', c_char * 36),
|
| 2113 |
+
]
|
| 2114 |
+
assert sizeof(_opaque_pthread_attr_t) == 40, sizeof(_opaque_pthread_attr_t)
|
| 2115 |
+
assert alignment(_opaque_pthread_attr_t) == 4, alignment(_opaque_pthread_attr_t)
|
| 2116 |
+
class _opaque_pthread_cond_t(Structure):
|
| 2117 |
+
pass
|
| 2118 |
+
_opaque_pthread_cond_t._fields_ = [
|
| 2119 |
+
('__sig', c_long),
|
| 2120 |
+
('__opaque', c_char * 24),
|
| 2121 |
+
]
|
| 2122 |
+
assert sizeof(_opaque_pthread_cond_t) == 28, sizeof(_opaque_pthread_cond_t)
|
| 2123 |
+
assert alignment(_opaque_pthread_cond_t) == 4, alignment(_opaque_pthread_cond_t)
|
| 2124 |
+
class _opaque_pthread_condattr_t(Structure):
|
| 2125 |
+
pass
|
| 2126 |
+
_opaque_pthread_condattr_t._fields_ = [
|
| 2127 |
+
('__sig', c_long),
|
| 2128 |
+
('__opaque', c_char * 4),
|
| 2129 |
+
]
|
| 2130 |
+
assert sizeof(_opaque_pthread_condattr_t) == 8, sizeof(_opaque_pthread_condattr_t)
|
| 2131 |
+
assert alignment(_opaque_pthread_condattr_t) == 4, alignment(_opaque_pthread_condattr_t)
|
| 2132 |
+
class _opaque_pthread_mutex_t(Structure):
|
| 2133 |
+
pass
|
| 2134 |
+
_opaque_pthread_mutex_t._fields_ = [
|
| 2135 |
+
('__sig', c_long),
|
| 2136 |
+
('__opaque', c_char * 40),
|
| 2137 |
+
]
|
| 2138 |
+
assert sizeof(_opaque_pthread_mutex_t) == 44, sizeof(_opaque_pthread_mutex_t)
|
| 2139 |
+
assert alignment(_opaque_pthread_mutex_t) == 4, alignment(_opaque_pthread_mutex_t)
|
| 2140 |
+
class _opaque_pthread_mutexattr_t(Structure):
|
| 2141 |
+
pass
|
| 2142 |
+
_opaque_pthread_mutexattr_t._fields_ = [
|
| 2143 |
+
('__sig', c_long),
|
| 2144 |
+
('__opaque', c_char * 8),
|
| 2145 |
+
]
|
| 2146 |
+
assert sizeof(_opaque_pthread_mutexattr_t) == 12, sizeof(_opaque_pthread_mutexattr_t)
|
| 2147 |
+
assert alignment(_opaque_pthread_mutexattr_t) == 4, alignment(_opaque_pthread_mutexattr_t)
|
| 2148 |
+
class _opaque_pthread_once_t(Structure):
|
| 2149 |
+
pass
|
| 2150 |
+
_opaque_pthread_once_t._fields_ = [
|
| 2151 |
+
('__sig', c_long),
|
| 2152 |
+
('__opaque', c_char * 4),
|
| 2153 |
+
]
|
| 2154 |
+
assert sizeof(_opaque_pthread_once_t) == 8, sizeof(_opaque_pthread_once_t)
|
| 2155 |
+
assert alignment(_opaque_pthread_once_t) == 4, alignment(_opaque_pthread_once_t)
|
| 2156 |
+
class _opaque_pthread_rwlock_t(Structure):
|
| 2157 |
+
pass
|
| 2158 |
+
_opaque_pthread_rwlock_t._fields_ = [
|
| 2159 |
+
('__sig', c_long),
|
| 2160 |
+
('__opaque', c_char * 124),
|
| 2161 |
+
]
|
| 2162 |
+
assert sizeof(_opaque_pthread_rwlock_t) == 128, sizeof(_opaque_pthread_rwlock_t)
|
| 2163 |
+
assert alignment(_opaque_pthread_rwlock_t) == 4, alignment(_opaque_pthread_rwlock_t)
|
| 2164 |
+
class _opaque_pthread_rwlockattr_t(Structure):
|
| 2165 |
+
pass
|
| 2166 |
+
_opaque_pthread_rwlockattr_t._fields_ = [
|
| 2167 |
+
('__sig', c_long),
|
| 2168 |
+
('__opaque', c_char * 12),
|
| 2169 |
+
]
|
| 2170 |
+
assert sizeof(_opaque_pthread_rwlockattr_t) == 16, sizeof(_opaque_pthread_rwlockattr_t)
|
| 2171 |
+
assert alignment(_opaque_pthread_rwlockattr_t) == 4, alignment(_opaque_pthread_rwlockattr_t)
|
| 2172 |
+
class _opaque_pthread_t(Structure):
|
| 2173 |
+
pass
|
| 2174 |
+
_opaque_pthread_t._fields_ = [
|
| 2175 |
+
('__sig', c_long),
|
| 2176 |
+
('__cleanup_stack', POINTER(__darwin_pthread_handler_rec)),
|
| 2177 |
+
('__opaque', c_char * 596),
|
| 2178 |
+
]
|
| 2179 |
+
assert sizeof(_opaque_pthread_t) == 604, sizeof(_opaque_pthread_t)
|
| 2180 |
+
assert alignment(_opaque_pthread_t) == 4, alignment(_opaque_pthread_t)
|
| 2181 |
+
__darwin_blkcnt_t = __int64_t
|
| 2182 |
+
__darwin_blksize_t = __int32_t
|
| 2183 |
+
__darwin_fsblkcnt_t = c_uint
|
| 2184 |
+
__darwin_fsfilcnt_t = c_uint
|
| 2185 |
+
__darwin_gid_t = __uint32_t
|
| 2186 |
+
__darwin_id_t = __uint32_t
|
| 2187 |
+
__darwin_ino_t = __uint32_t
|
| 2188 |
+
__darwin_mach_port_name_t = __darwin_natural_t
|
| 2189 |
+
__darwin_mach_port_t = __darwin_mach_port_name_t
|
| 2190 |
+
__darwin_mcontext_t = POINTER(mcontext)
|
| 2191 |
+
__darwin_mcontext64_t = POINTER(mcontext64)
|
| 2192 |
+
__darwin_pid_t = __int32_t
|
| 2193 |
+
__darwin_pthread_attr_t = _opaque_pthread_attr_t
|
| 2194 |
+
__darwin_pthread_cond_t = _opaque_pthread_cond_t
|
| 2195 |
+
__darwin_pthread_condattr_t = _opaque_pthread_condattr_t
|
| 2196 |
+
__darwin_pthread_key_t = c_ulong
|
| 2197 |
+
__darwin_pthread_mutex_t = _opaque_pthread_mutex_t
|
| 2198 |
+
__darwin_pthread_mutexattr_t = _opaque_pthread_mutexattr_t
|
| 2199 |
+
__darwin_pthread_once_t = _opaque_pthread_once_t
|
| 2200 |
+
__darwin_pthread_rwlock_t = _opaque_pthread_rwlock_t
|
| 2201 |
+
__darwin_pthread_rwlockattr_t = _opaque_pthread_rwlockattr_t
|
| 2202 |
+
__darwin_pthread_t = POINTER(_opaque_pthread_t)
|
| 2203 |
+
__darwin_sigset_t = __uint32_t
|
| 2204 |
+
__darwin_suseconds_t = __int32_t
|
| 2205 |
+
__darwin_uid_t = __uint32_t
|
| 2206 |
+
__darwin_useconds_t = __uint32_t
|
| 2207 |
+
__darwin_uuid_t = c_ubyte * 16
|
| 2208 |
+
class sigaltstack(Structure):
|
| 2209 |
+
pass
|
| 2210 |
+
sigaltstack._fields_ = [
|
| 2211 |
+
('ss_sp', c_void_p),
|
| 2212 |
+
('ss_size', __darwin_size_t),
|
| 2213 |
+
('ss_flags', c_int),
|
| 2214 |
+
]
|
| 2215 |
+
assert sizeof(sigaltstack) == 12, sizeof(sigaltstack)
|
| 2216 |
+
assert alignment(sigaltstack) == 4, alignment(sigaltstack)
|
| 2217 |
+
__darwin_stack_t = sigaltstack
|
| 2218 |
+
class ucontext(Structure):
|
| 2219 |
+
pass
|
| 2220 |
+
ucontext._fields_ = [
|
| 2221 |
+
('uc_onstack', c_int),
|
| 2222 |
+
('uc_sigmask', __darwin_sigset_t),
|
| 2223 |
+
('uc_stack', __darwin_stack_t),
|
| 2224 |
+
('uc_link', POINTER(ucontext)),
|
| 2225 |
+
('uc_mcsize', __darwin_size_t),
|
| 2226 |
+
('uc_mcontext', __darwin_mcontext_t),
|
| 2227 |
+
]
|
| 2228 |
+
assert sizeof(ucontext) == 32, sizeof(ucontext)
|
| 2229 |
+
assert alignment(ucontext) == 4, alignment(ucontext)
|
| 2230 |
+
__darwin_ucontext_t = ucontext
|
| 2231 |
+
class ucontext64(Structure):
|
| 2232 |
+
pass
|
| 2233 |
+
ucontext64._fields_ = [
|
| 2234 |
+
('uc_onstack', c_int),
|
| 2235 |
+
('uc_sigmask', __darwin_sigset_t),
|
| 2236 |
+
('uc_stack', __darwin_stack_t),
|
| 2237 |
+
('uc_link', POINTER(ucontext64)),
|
| 2238 |
+
('uc_mcsize', __darwin_size_t),
|
| 2239 |
+
('uc_mcontext64', __darwin_mcontext64_t),
|
| 2240 |
+
]
|
| 2241 |
+
assert sizeof(ucontext64) == 32, sizeof(ucontext64)
|
| 2242 |
+
assert alignment(ucontext64) == 4, alignment(ucontext64)
|
| 2243 |
+
__darwin_ucontext64_t = ucontext64
|
| 2244 |
+
class timeval(Structure):
|
| 2245 |
+
pass
|
| 2246 |
+
timeval._fields_ = [
|
| 2247 |
+
('tv_sec', __darwin_time_t),
|
| 2248 |
+
('tv_usec', __darwin_suseconds_t),
|
| 2249 |
+
]
|
| 2250 |
+
assert sizeof(timeval) == 8, sizeof(timeval)
|
| 2251 |
+
assert alignment(timeval) == 4, alignment(timeval)
|
| 2252 |
+
rlim_t = __int64_t
|
| 2253 |
+
class rusage(Structure):
|
| 2254 |
+
pass
|
| 2255 |
+
rusage._fields_ = [
|
| 2256 |
+
('ru_utime', timeval),
|
| 2257 |
+
('ru_stime', timeval),
|
| 2258 |
+
('ru_maxrss', c_long),
|
| 2259 |
+
('ru_ixrss', c_long),
|
| 2260 |
+
('ru_idrss', c_long),
|
| 2261 |
+
('ru_isrss', c_long),
|
| 2262 |
+
('ru_minflt', c_long),
|
| 2263 |
+
('ru_majflt', c_long),
|
| 2264 |
+
('ru_nswap', c_long),
|
| 2265 |
+
('ru_inblock', c_long),
|
| 2266 |
+
('ru_oublock', c_long),
|
| 2267 |
+
('ru_msgsnd', c_long),
|
| 2268 |
+
('ru_msgrcv', c_long),
|
| 2269 |
+
('ru_nsignals', c_long),
|
| 2270 |
+
('ru_nvcsw', c_long),
|
| 2271 |
+
('ru_nivcsw', c_long),
|
| 2272 |
+
]
|
| 2273 |
+
assert sizeof(rusage) == 72, sizeof(rusage)
|
| 2274 |
+
assert alignment(rusage) == 4, alignment(rusage)
|
| 2275 |
+
class rlimit(Structure):
|
| 2276 |
+
pass
|
| 2277 |
+
rlimit._pack_ = 4
|
| 2278 |
+
rlimit._fields_ = [
|
| 2279 |
+
('rlim_cur', rlim_t),
|
| 2280 |
+
('rlim_max', rlim_t),
|
| 2281 |
+
]
|
| 2282 |
+
assert sizeof(rlimit) == 16, sizeof(rlimit)
|
| 2283 |
+
assert alignment(rlimit) == 4, alignment(rlimit)
|
| 2284 |
+
mcontext_t = __darwin_mcontext_t
|
| 2285 |
+
mcontext64_t = __darwin_mcontext64_t
|
| 2286 |
+
pthread_attr_t = __darwin_pthread_attr_t
|
| 2287 |
+
sigset_t = __darwin_sigset_t
|
| 2288 |
+
ucontext_t = __darwin_ucontext_t
|
| 2289 |
+
ucontext64_t = __darwin_ucontext64_t
|
| 2290 |
+
uid_t = __darwin_uid_t
|
| 2291 |
+
class sigval(Union):
|
| 2292 |
+
pass
|
| 2293 |
+
sigval._fields_ = [
|
| 2294 |
+
('sival_int', c_int),
|
| 2295 |
+
('sival_ptr', c_void_p),
|
| 2296 |
+
]
|
| 2297 |
+
assert sizeof(sigval) == 4, sizeof(sigval)
|
| 2298 |
+
assert alignment(sigval) == 4, alignment(sigval)
|
| 2299 |
+
class sigevent(Structure):
|
| 2300 |
+
pass
|
| 2301 |
+
sigevent._fields_ = [
|
| 2302 |
+
('sigev_notify', c_int),
|
| 2303 |
+
('sigev_signo', c_int),
|
| 2304 |
+
('sigev_value', sigval),
|
| 2305 |
+
('sigev_notify_function', CFUNCTYPE(None, sigval)),
|
| 2306 |
+
('sigev_notify_attributes', POINTER(pthread_attr_t)),
|
| 2307 |
+
]
|
| 2308 |
+
assert sizeof(sigevent) == 20, sizeof(sigevent)
|
| 2309 |
+
assert alignment(sigevent) == 4, alignment(sigevent)
|
| 2310 |
+
class __siginfo(Structure):
|
| 2311 |
+
pass
|
| 2312 |
+
pid_t = __darwin_pid_t
|
| 2313 |
+
__siginfo._fields_ = [
|
| 2314 |
+
('si_signo', c_int),
|
| 2315 |
+
('si_errno', c_int),
|
| 2316 |
+
('si_code', c_int),
|
| 2317 |
+
('si_pid', pid_t),
|
| 2318 |
+
('si_uid', uid_t),
|
| 2319 |
+
('si_status', c_int),
|
| 2320 |
+
('si_addr', c_void_p),
|
| 2321 |
+
('si_value', sigval),
|
| 2322 |
+
('si_band', c_long),
|
| 2323 |
+
('pad', c_ulong * 7),
|
| 2324 |
+
]
|
| 2325 |
+
assert sizeof(__siginfo) == 64, sizeof(__siginfo)
|
| 2326 |
+
assert alignment(__siginfo) == 4, alignment(__siginfo)
|
| 2327 |
+
siginfo_t = __siginfo
|
| 2328 |
+
class __sigaction_u(Union):
|
| 2329 |
+
pass
|
| 2330 |
+
__sigaction_u._fields_ = [
|
| 2331 |
+
('__sa_handler', CFUNCTYPE(None, c_int)),
|
| 2332 |
+
('__sa_sigaction', CFUNCTYPE(None, c_int, POINTER(__siginfo), c_void_p)),
|
| 2333 |
+
]
|
| 2334 |
+
assert sizeof(__sigaction_u) == 4, sizeof(__sigaction_u)
|
| 2335 |
+
assert alignment(__sigaction_u) == 4, alignment(__sigaction_u)
|
| 2336 |
+
class __sigaction(Structure):
|
| 2337 |
+
pass
|
| 2338 |
+
__sigaction._fields_ = [
|
| 2339 |
+
('__sigaction_u', __sigaction_u),
|
| 2340 |
+
('sa_tramp', CFUNCTYPE(None, c_void_p, c_int, c_int, POINTER(siginfo_t), c_void_p)),
|
| 2341 |
+
('sa_mask', sigset_t),
|
| 2342 |
+
('sa_flags', c_int),
|
| 2343 |
+
]
|
| 2344 |
+
assert sizeof(__sigaction) == 16, sizeof(__sigaction)
|
| 2345 |
+
assert alignment(__sigaction) == 4, alignment(__sigaction)
|
| 2346 |
+
class sigaction(Structure):
|
| 2347 |
+
pass
|
| 2348 |
+
sigaction._fields_ = [
|
| 2349 |
+
('__sigaction_u', __sigaction_u),
|
| 2350 |
+
('sa_mask', sigset_t),
|
| 2351 |
+
('sa_flags', c_int),
|
| 2352 |
+
]
|
| 2353 |
+
assert sizeof(sigaction) == 12, sizeof(sigaction)
|
| 2354 |
+
assert alignment(sigaction) == 4, alignment(sigaction)
|
| 2355 |
+
sig_t = CFUNCTYPE(None, c_int)
|
| 2356 |
+
stack_t = __darwin_stack_t
|
| 2357 |
+
class sigvec(Structure):
|
| 2358 |
+
pass
|
| 2359 |
+
sigvec._fields_ = [
|
| 2360 |
+
('sv_handler', CFUNCTYPE(None, c_int)),
|
| 2361 |
+
('sv_mask', c_int),
|
| 2362 |
+
('sv_flags', c_int),
|
| 2363 |
+
]
|
| 2364 |
+
assert sizeof(sigvec) == 12, sizeof(sigvec)
|
| 2365 |
+
assert alignment(sigvec) == 4, alignment(sigvec)
|
| 2366 |
+
class sigstack(Structure):
|
| 2367 |
+
pass
|
| 2368 |
+
sigstack._fields_ = [
|
| 2369 |
+
('ss_sp', STRING),
|
| 2370 |
+
('ss_onstack', c_int),
|
| 2371 |
+
]
|
| 2372 |
+
assert sizeof(sigstack) == 8, sizeof(sigstack)
|
| 2373 |
+
assert alignment(sigstack) == 4, alignment(sigstack)
|
| 2374 |
+
u_char = c_ubyte
|
| 2375 |
+
u_short = c_ushort
|
| 2376 |
+
u_int = c_uint
|
| 2377 |
+
u_long = c_ulong
|
| 2378 |
+
ushort = c_ushort
|
| 2379 |
+
uint = c_uint
|
| 2380 |
+
u_quad_t = u_int64_t
|
| 2381 |
+
quad_t = int64_t
|
| 2382 |
+
qaddr_t = POINTER(quad_t)
|
| 2383 |
+
caddr_t = STRING
|
| 2384 |
+
daddr_t = int32_t
|
| 2385 |
+
fixpt_t = u_int32_t
|
| 2386 |
+
blkcnt_t = __darwin_blkcnt_t
|
| 2387 |
+
blksize_t = __darwin_blksize_t
|
| 2388 |
+
gid_t = __darwin_gid_t
|
| 2389 |
+
in_addr_t = __uint32_t
|
| 2390 |
+
in_port_t = __uint16_t
|
| 2391 |
+
ino_t = __darwin_ino_t
|
| 2392 |
+
key_t = __int32_t
|
| 2393 |
+
nlink_t = __uint16_t
|
| 2394 |
+
off_t = __darwin_off_t
|
| 2395 |
+
segsz_t = int32_t
|
| 2396 |
+
swblk_t = int32_t
|
| 2397 |
+
clock_t = __darwin_clock_t
|
| 2398 |
+
ssize_t = __darwin_ssize_t
|
| 2399 |
+
useconds_t = __darwin_useconds_t
|
| 2400 |
+
suseconds_t = __darwin_suseconds_t
|
| 2401 |
+
fd_mask = __int32_t
|
| 2402 |
+
class fd_set(Structure):
|
| 2403 |
+
pass
|
| 2404 |
+
fd_set._fields_ = [
|
| 2405 |
+
('fds_bits', __int32_t * 32),
|
| 2406 |
+
]
|
| 2407 |
+
assert sizeof(fd_set) == 128, sizeof(fd_set)
|
| 2408 |
+
assert alignment(fd_set) == 4, alignment(fd_set)
|
| 2409 |
+
pthread_cond_t = __darwin_pthread_cond_t
|
| 2410 |
+
pthread_condattr_t = __darwin_pthread_condattr_t
|
| 2411 |
+
pthread_mutex_t = __darwin_pthread_mutex_t
|
| 2412 |
+
pthread_mutexattr_t = __darwin_pthread_mutexattr_t
|
| 2413 |
+
pthread_once_t = __darwin_pthread_once_t
|
| 2414 |
+
pthread_rwlock_t = __darwin_pthread_rwlock_t
|
| 2415 |
+
pthread_rwlockattr_t = __darwin_pthread_rwlockattr_t
|
| 2416 |
+
pthread_t = __darwin_pthread_t
|
| 2417 |
+
pthread_key_t = __darwin_pthread_key_t
|
| 2418 |
+
fsblkcnt_t = __darwin_fsblkcnt_t
|
| 2419 |
+
fsfilcnt_t = __darwin_fsfilcnt_t
|
| 2420 |
+
|
| 2421 |
+
# values for enumeration 'idtype_t'
|
| 2422 |
+
idtype_t = c_int # enum
|
| 2423 |
+
id_t = __darwin_id_t
|
| 2424 |
+
class wait(Union):
|
| 2425 |
+
pass
|
| 2426 |
+
class N4wait3DOLLAR_3E(Structure):
|
| 2427 |
+
pass
|
| 2428 |
+
N4wait3DOLLAR_3E._fields_ = [
|
| 2429 |
+
('w_Termsig', c_uint, 7),
|
| 2430 |
+
('w_Coredump', c_uint, 1),
|
| 2431 |
+
('w_Retcode', c_uint, 8),
|
| 2432 |
+
('w_Filler', c_uint, 16),
|
| 2433 |
+
]
|
| 2434 |
+
assert sizeof(N4wait3DOLLAR_3E) == 4, sizeof(N4wait3DOLLAR_3E)
|
| 2435 |
+
assert alignment(N4wait3DOLLAR_3E) == 4, alignment(N4wait3DOLLAR_3E)
|
| 2436 |
+
class N4wait3DOLLAR_4E(Structure):
|
| 2437 |
+
pass
|
| 2438 |
+
N4wait3DOLLAR_4E._fields_ = [
|
| 2439 |
+
('w_Stopval', c_uint, 8),
|
| 2440 |
+
('w_Stopsig', c_uint, 8),
|
| 2441 |
+
('w_Filler', c_uint, 16),
|
| 2442 |
+
]
|
| 2443 |
+
assert sizeof(N4wait3DOLLAR_4E) == 4, sizeof(N4wait3DOLLAR_4E)
|
| 2444 |
+
assert alignment(N4wait3DOLLAR_4E) == 4, alignment(N4wait3DOLLAR_4E)
|
| 2445 |
+
wait._fields_ = [
|
| 2446 |
+
('w_status', c_int),
|
| 2447 |
+
('w_T', N4wait3DOLLAR_3E),
|
| 2448 |
+
('w_S', N4wait3DOLLAR_4E),
|
| 2449 |
+
]
|
| 2450 |
+
assert sizeof(wait) == 4, sizeof(wait)
|
| 2451 |
+
assert alignment(wait) == 4, alignment(wait)
|
| 2452 |
+
class timespec(Structure):
|
| 2453 |
+
pass
|
| 2454 |
+
timespec._fields_ = [
|
| 2455 |
+
('tv_sec', time_t),
|
| 2456 |
+
('tv_nsec', c_long),
|
| 2457 |
+
]
|
| 2458 |
+
assert sizeof(timespec) == 8, sizeof(timespec)
|
| 2459 |
+
assert alignment(timespec) == 4, alignment(timespec)
|
| 2460 |
+
class tm(Structure):
|
| 2461 |
+
pass
|
| 2462 |
+
tm._fields_ = [
|
| 2463 |
+
('tm_sec', c_int),
|
| 2464 |
+
('tm_min', c_int),
|
| 2465 |
+
('tm_hour', c_int),
|
| 2466 |
+
('tm_mday', c_int),
|
| 2467 |
+
('tm_mon', c_int),
|
| 2468 |
+
('tm_year', c_int),
|
| 2469 |
+
('tm_wday', c_int),
|
| 2470 |
+
('tm_yday', c_int),
|
| 2471 |
+
('tm_isdst', c_int),
|
| 2472 |
+
('tm_gmtoff', c_long),
|
| 2473 |
+
('tm_zone', STRING),
|
| 2474 |
+
]
|
| 2475 |
+
assert sizeof(tm) == 44, sizeof(tm)
|
| 2476 |
+
assert alignment(tm) == 4, alignment(tm)
|
| 2477 |
+
__gnuc_va_list = STRING
|
| 2478 |
+
ptrdiff_t = c_int
|
| 2479 |
+
int8_t = c_byte
|
| 2480 |
+
int16_t = c_short
|
| 2481 |
+
uint8_t = c_ubyte
|
| 2482 |
+
uint16_t = c_ushort
|
| 2483 |
+
uint32_t = c_uint
|
| 2484 |
+
uint64_t = c_ulonglong
|
| 2485 |
+
int_least8_t = int8_t
|
| 2486 |
+
int_least16_t = int16_t
|
| 2487 |
+
int_least32_t = int32_t
|
| 2488 |
+
int_least64_t = int64_t
|
| 2489 |
+
uint_least8_t = uint8_t
|
| 2490 |
+
uint_least16_t = uint16_t
|
| 2491 |
+
uint_least32_t = uint32_t
|
| 2492 |
+
uint_least64_t = uint64_t
|
| 2493 |
+
int_fast8_t = int8_t
|
| 2494 |
+
int_fast16_t = int16_t
|
| 2495 |
+
int_fast32_t = int32_t
|
| 2496 |
+
int_fast64_t = int64_t
|
| 2497 |
+
uint_fast8_t = uint8_t
|
| 2498 |
+
uint_fast16_t = uint16_t
|
| 2499 |
+
uint_fast32_t = uint32_t
|
| 2500 |
+
uint_fast64_t = uint64_t
|
| 2501 |
+
intptr_t = c_long
|
| 2502 |
+
uintptr_t = c_ulong
|
| 2503 |
+
intmax_t = c_longlong
|
| 2504 |
+
uintmax_t = c_ulonglong
|
| 2505 |
+
__all__ = ['ENGINE', 'pkcs7_enc_content_st', '__int16_t',
|
| 2506 |
+
'X509_REVOKED', 'SSL_CTX', 'UIT_BOOLEAN',
|
| 2507 |
+
'__darwin_time_t', 'ucontext64_t', 'int_fast32_t',
|
| 2508 |
+
'pem_ctx_st', 'uint8_t', 'fpos_t', 'X509', 'COMP_CTX',
|
| 2509 |
+
'tm', 'N10pem_ctx_st4DOLLAR_17E', 'swblk_t',
|
| 2510 |
+
'ASN1_TEMPLATE', '__darwin_pthread_t', 'fixpt_t',
|
| 2511 |
+
'BIO_METHOD', 'ASN1_PRINTABLESTRING', 'EVP_ENCODE_CTX',
|
| 2512 |
+
'dh_method', 'bio_f_buffer_ctx_struct', 'in_port_t',
|
| 2513 |
+
'X509_SIG', '__darwin_ssize_t', '__darwin_sigset_t',
|
| 2514 |
+
'wait', 'uint_fast16_t', 'N12asn1_type_st4DOLLAR_11E',
|
| 2515 |
+
'uint_least8_t', 'pthread_rwlock_t', 'ASN1_IA5STRING',
|
| 2516 |
+
'fsfilcnt_t', 'ucontext', '__uint64_t', 'timespec',
|
| 2517 |
+
'x509_cinf_st', 'COMP_METHOD', 'MD5_CTX', 'buf_mem_st',
|
| 2518 |
+
'ASN1_ENCODING_st', 'PBEPARAM', 'X509_NAME_ENTRY',
|
| 2519 |
+
'__darwin_va_list', 'ucontext_t', 'lhash_st',
|
| 2520 |
+
'N4wait3DOLLAR_4E', '__darwin_uuid_t',
|
| 2521 |
+
'_ossl_old_des_ks_struct', 'id_t', 'ASN1_BIT_STRING',
|
| 2522 |
+
'va_list', '__darwin_wchar_t', 'pthread_key_t',
|
| 2523 |
+
'pkcs7_signer_info_st', 'ASN1_METHOD', 'DSA_SIG', 'DSA',
|
| 2524 |
+
'UIT_NONE', 'pthread_t', '__darwin_useconds_t',
|
| 2525 |
+
'uint_fast8_t', 'UI_STRING', 'DES_cblock',
|
| 2526 |
+
'__darwin_mcontext64_t', 'rlim_t', 'PEM_Encode_Seal_st',
|
| 2527 |
+
'SHAstate_st', 'u_quad_t', 'openssl_fptr',
|
| 2528 |
+
'_opaque_pthread_rwlockattr_t',
|
| 2529 |
+
'N18x509_attributes_st4DOLLAR_13E',
|
| 2530 |
+
'__darwin_pthread_rwlock_t', 'daddr_t', 'ui_string_st',
|
| 2531 |
+
'x509_file_st', 'X509_req_info_st', 'int_least64_t',
|
| 2532 |
+
'evp_Encode_Ctx_st', 'X509_OBJECTS', 'CRYPTO_EX_DATA',
|
| 2533 |
+
'__int8_t', 'AUTHORITY_KEYID_st', '_opaque_pthread_attr_t',
|
| 2534 |
+
'sigstack', 'EVP_CIPHER_CTX', 'X509_extension_st', 'pid_t',
|
| 2535 |
+
'RSA_METHOD', 'PEM_USER', 'pem_recip_st', 'env_md_ctx_st',
|
| 2536 |
+
'rc5_key_st', 'ui_st', 'X509_PUBKEY', 'u_int8_t',
|
| 2537 |
+
'ASN1_ITEM_st', 'pkcs7_recip_info_st', 'ssl2_state_st',
|
| 2538 |
+
'off_t', 'N10ssl_ctx_st4DOLLAR_18E', 'crypto_ex_data_st',
|
| 2539 |
+
'ui_method_st', '__darwin_pthread_rwlockattr_t',
|
| 2540 |
+
'CRYPTO_EX_dup', '__darwin_ino_t', '__sFILE',
|
| 2541 |
+
'OSUnknownByteOrder', 'BN_MONT_CTX', 'ASN1_NULL', 'time_t',
|
| 2542 |
+
'CRYPTO_EX_new', 'asn1_type_st', 'CRYPTO_EX_DATA_FUNCS',
|
| 2543 |
+
'user_time_t', 'BIGNUM', 'pthread_rwlockattr_t',
|
| 2544 |
+
'ASN1_VALUE_st', 'DH_METHOD', '__darwin_off_t',
|
| 2545 |
+
'_opaque_pthread_t', 'bn_blinding_st', 'RSA', 'ssize_t',
|
| 2546 |
+
'mcontext64_t', 'user_long_t', 'fsblkcnt_t', 'cert_st',
|
| 2547 |
+
'__darwin_pthread_condattr_t', 'X509_PKEY',
|
| 2548 |
+
'__darwin_id_t', '__darwin_nl_item', 'SSL2_STATE', 'FILE',
|
| 2549 |
+
'pthread_mutexattr_t', 'size_t',
|
| 2550 |
+
'_ossl_old_des_key_schedule', 'pkcs7_issuer_and_serial_st',
|
| 2551 |
+
'sigval', 'CRYPTO_MEM_LEAK_CB', 'X509_NAME', 'blkcnt_t',
|
| 2552 |
+
'uint_least16_t', '__darwin_dev_t', 'evp_cipher_info_st',
|
| 2553 |
+
'BN_BLINDING', 'ssl3_state_st', 'uint_least64_t',
|
| 2554 |
+
'user_addr_t', 'DES_key_schedule', 'RIPEMD160_CTX',
|
| 2555 |
+
'u_char', 'X509_algor_st', 'uid_t', 'sess_cert_st',
|
| 2556 |
+
'u_int64_t', 'u_int16_t', 'sigset_t', '__darwin_ptrdiff_t',
|
| 2557 |
+
'ASN1_CTX', 'STACK', '__int32_t', 'UI_METHOD',
|
| 2558 |
+
'NETSCAPE_SPKI', 'UIT_PROMPT', 'st_CRYPTO_EX_DATA_IMPL',
|
| 2559 |
+
'cast_key_st', 'X509_HASH_DIR_CTX', 'sigevent',
|
| 2560 |
+
'user_ssize_t', 'clock_t', 'aes_key_st',
|
| 2561 |
+
'__darwin_socklen_t', '__darwin_intptr_t', 'int_fast64_t',
|
| 2562 |
+
'asn1_string_table_st', 'uint_fast32_t',
|
| 2563 |
+
'ASN1_VISIBLESTRING', 'DSA_SIG_st', 'obj_name_st',
|
| 2564 |
+
'X509_LOOKUP_METHOD', 'u_int32_t', 'EVP_CIPHER_INFO',
|
| 2565 |
+
'__gnuc_va_list', 'AES_KEY', 'PKCS7_ISSUER_AND_SERIAL',
|
| 2566 |
+
'BN_CTX', '__darwin_blkcnt_t', 'key_t', 'SHA_CTX',
|
| 2567 |
+
'pkcs7_signed_st', 'SSL', 'N10pem_ctx_st4DOLLAR_16E',
|
| 2568 |
+
'pthread_attr_t', 'EVP_MD', 'uint', 'ASN1_BOOLEAN',
|
| 2569 |
+
'ino_t', '__darwin_clock_t', 'ASN1_OCTET_STRING',
|
| 2570 |
+
'asn1_ctx_st', 'BIO_F_BUFFER_CTX', 'bn_mont_ctx_st',
|
| 2571 |
+
'X509_REQ_INFO', 'PEM_CTX', 'sigvec',
|
| 2572 |
+
'__darwin_pthread_mutexattr_t', 'x509_attributes_st',
|
| 2573 |
+
'stack_t', '__darwin_mode_t', '__mbstate_t',
|
| 2574 |
+
'asn1_object_st', 'ASN1_ENCODING', '__uint8_t',
|
| 2575 |
+
'LHASH_NODE', 'PKCS7_SIGNER_INFO', 'asn1_method_st',
|
| 2576 |
+
'stack_st', 'bio_info_cb', 'div_t', 'UIT_VERIFY',
|
| 2577 |
+
'PBEPARAM_st', 'N4wait3DOLLAR_3E', 'quad_t', '__siginfo',
|
| 2578 |
+
'__darwin_mbstate_t', 'rsa_st', 'ASN1_UNIVERSALSTRING',
|
| 2579 |
+
'uint64_t', 'ssl_comp_st', 'X509_OBJECT', 'pthread_cond_t',
|
| 2580 |
+
'DH', '__darwin_wctype_t', 'PKCS7_ENVELOPE', 'ASN1_TLC_st',
|
| 2581 |
+
'sig_atomic_t', 'BIO', 'nlink_t', 'BUF_MEM', 'SSL3_RECORD',
|
| 2582 |
+
'bio_method_st', 'timeval', 'UI_string_types', 'BIO_dummy',
|
| 2583 |
+
'ssl_ctx_st', 'NETSCAPE_CERT_SEQUENCE',
|
| 2584 |
+
'BIT_STRING_BITNAME_st', '__darwin_pthread_attr_t',
|
| 2585 |
+
'int8_t', '__darwin_wint_t', 'OBJ_NAME',
|
| 2586 |
+
'PKCS8_PRIV_KEY_INFO', 'PBE2PARAM_st',
|
| 2587 |
+
'LHASH_DOALL_FN_TYPE', 'x509_st', 'X509_VAL', 'dev_t',
|
| 2588 |
+
'ASN1_TEMPLATE_st', 'MD5state_st', '__uint16_t',
|
| 2589 |
+
'LHASH_DOALL_ARG_FN_TYPE', 'mdc2_ctx_st', 'SSL3_STATE',
|
| 2590 |
+
'ssl3_buffer_st', 'ASN1_ITEM_EXP',
|
| 2591 |
+
'_opaque_pthread_condattr_t', 'mode_t', 'ASN1_VALUE',
|
| 2592 |
+
'qaddr_t', '__darwin_gid_t', 'EVP_PKEY', 'CRYPTO_EX_free',
|
| 2593 |
+
'_ossl_old_des_cblock', 'X509_INFO', 'asn1_string_st',
|
| 2594 |
+
'intptr_t', 'UIT_INFO', 'int_fast8_t', 'sigaltstack',
|
| 2595 |
+
'env_md_st', 'LHASH', '__darwin_ucontext_t',
|
| 2596 |
+
'PKCS7_SIGN_ENVELOPE', '__darwin_mcontext_t', 'ct_rune_t',
|
| 2597 |
+
'MD2_CTX', 'pthread_once_t', 'SSL3_BUFFER', 'fd_mask',
|
| 2598 |
+
'ASN1_TYPE', 'PKCS7_SIGNED', 'ssl3_record_st', 'BF_KEY',
|
| 2599 |
+
'MD4state_st', 'MD4_CTX', 'int16_t', 'SSL_CIPHER',
|
| 2600 |
+
'rune_t', 'X509_TRUST', 'siginfo_t', 'X509_STORE',
|
| 2601 |
+
'__sbuf', 'X509_STORE_CTX', '__darwin_blksize_t', 'ldiv_t',
|
| 2602 |
+
'ASN1_TIME', 'SSL_METHOD', 'X509_LOOKUP',
|
| 2603 |
+
'Netscape_spki_st', 'P_PID', 'sigaction', 'sig_t',
|
| 2604 |
+
'hostent', 'x509_cert_aux_st', '_opaque_pthread_cond_t',
|
| 2605 |
+
'segsz_t', 'ushort', '__darwin_ct_rune_t', 'fd_set',
|
| 2606 |
+
'BN_RECP_CTX', 'x509_lookup_st', 'uint16_t', 'pkcs7_st',
|
| 2607 |
+
'asn1_header_st', '__darwin_pthread_key_t',
|
| 2608 |
+
'x509_trust_st', '__darwin_pthread_handler_rec', 'int32_t',
|
| 2609 |
+
'X509_CRL_INFO', 'N11evp_pkey_st4DOLLAR_12E', 'MDC2_CTX',
|
| 2610 |
+
'N23_ossl_old_des_ks_struct4DOLLAR_10E', 'ASN1_HEADER',
|
| 2611 |
+
'X509_crl_info_st', 'LHASH_HASH_FN_TYPE',
|
| 2612 |
+
'_opaque_pthread_mutexattr_t', 'ssl_st',
|
| 2613 |
+
'N8pkcs7_st4DOLLAR_15E', 'evp_pkey_st',
|
| 2614 |
+
'pkcs7_signedandenveloped_st', '__darwin_mach_port_t',
|
| 2615 |
+
'EVP_PBE_KEYGEN', '_opaque_pthread_mutex_t',
|
| 2616 |
+
'ASN1_UTCTIME', 'mcontext', 'crypto_ex_data_func_st',
|
| 2617 |
+
'u_long', 'PBKDF2PARAM_st', 'rc4_key_st', 'DSA_METHOD',
|
| 2618 |
+
'EVP_CIPHER', 'BIT_STRING_BITNAME', 'PKCS7_RECIP_INFO',
|
| 2619 |
+
'ssl3_enc_method', 'X509_CERT_AUX', 'uintmax_t',
|
| 2620 |
+
'int_fast16_t', 'RC5_32_KEY', 'ucontext64', 'ASN1_INTEGER',
|
| 2621 |
+
'u_short', 'N14x509_object_st4DOLLAR_14E', 'mcontext64',
|
| 2622 |
+
'X509_sig_st', 'ASN1_GENERALSTRING', 'PKCS7', '__sFILEX',
|
| 2623 |
+
'X509_name_entry_st', 'ssl_session_st', 'caddr_t',
|
| 2624 |
+
'bignum_st', 'X509_CINF', '__darwin_pthread_cond_t',
|
| 2625 |
+
'ASN1_TLC', 'PKCS7_ENCRYPT', 'NETSCAPE_SPKAC',
|
| 2626 |
+
'Netscape_spkac_st', 'idtype_t', 'UIT_ERROR',
|
| 2627 |
+
'uint_fast64_t', 'in_addr_t', 'pthread_mutex_t',
|
| 2628 |
+
'__int64_t', 'ASN1_BMPSTRING', 'uint32_t',
|
| 2629 |
+
'PEM_ENCODE_SEAL_CTX', 'suseconds_t', 'ASN1_OBJECT',
|
| 2630 |
+
'X509_val_st', 'private_key_st', 'CRYPTO_dynlock',
|
| 2631 |
+
'X509_objects_st', 'CRYPTO_EX_DATA_IMPL',
|
| 2632 |
+
'pthread_condattr_t', 'PKCS7_DIGEST', 'uint_least32_t',
|
| 2633 |
+
'ASN1_STRING', '__uint32_t', 'P_PGID', 'rsa_meth_st',
|
| 2634 |
+
'X509_crl_st', 'RC2_KEY', '__darwin_fsfilcnt_t',
|
| 2635 |
+
'X509_revoked_st', 'PBE2PARAM', 'blksize_t',
|
| 2636 |
+
'Netscape_certificate_sequence', 'ssl_cipher_st',
|
| 2637 |
+
'bignum_ctx', 'register_t', 'ASN1_UTF8STRING',
|
| 2638 |
+
'pkcs7_encrypted_st', 'RC4_KEY', '__darwin_ucontext64_t',
|
| 2639 |
+
'N13ssl2_state_st4DOLLAR_19E', 'bn_recp_ctx_st',
|
| 2640 |
+
'CAST_KEY', 'X509_ATTRIBUTE', '__darwin_suseconds_t',
|
| 2641 |
+
'__sigaction', 'user_ulong_t', 'syscall_arg_t',
|
| 2642 |
+
'evp_cipher_ctx_st', 'X509_ALGOR', 'mcontext_t',
|
| 2643 |
+
'const_DES_cblock', '__darwin_fsblkcnt_t', 'dsa_st',
|
| 2644 |
+
'int_least8_t', 'MD2state_st', 'X509_EXTENSION',
|
| 2645 |
+
'GEN_SESSION_CB', 'int_least16_t', '__darwin_wctrans_t',
|
| 2646 |
+
'PBKDF2PARAM', 'x509_lookup_method_st', 'pem_password_cb',
|
| 2647 |
+
'X509_info_st', 'x509_store_st', '__darwin_natural_t',
|
| 2648 |
+
'X509_pubkey_st', 'pkcs7_digest_st', '__darwin_size_t',
|
| 2649 |
+
'ASN1_STRING_TABLE', 'OSLittleEndian', 'RIPEMD160state_st',
|
| 2650 |
+
'pkcs7_enveloped_st', 'UI', 'ptrdiff_t', 'X509_REQ',
|
| 2651 |
+
'CRYPTO_dynlock_value', 'X509_req_st', 'x509_store_ctx_st',
|
| 2652 |
+
'N13ssl3_state_st4DOLLAR_20E', 'lhash_node_st',
|
| 2653 |
+
'__darwin_pthread_mutex_t', 'LHASH_COMP_FN_TYPE',
|
| 2654 |
+
'__darwin_rune_t', 'rlimit', '__darwin_pthread_once_t',
|
| 2655 |
+
'OSBigEndian', 'uintptr_t', '__darwin_uid_t', 'u_int',
|
| 2656 |
+
'ASN1_T61STRING', 'gid_t', 'ssl_method_st', 'ASN1_ITEM',
|
| 2657 |
+
'ASN1_ENUMERATED', '_opaque_pthread_rwlock_t',
|
| 2658 |
+
'pkcs8_priv_key_info_st', 'intmax_t', 'sigcontext',
|
| 2659 |
+
'X509_CRL', 'rc2_key_st', 'engine_st', 'x509_object_st',
|
| 2660 |
+
'_opaque_pthread_once_t', 'DES_ks', 'SSL_COMP',
|
| 2661 |
+
'dsa_method', 'int64_t', 'bio_st', 'bf_key_st',
|
| 2662 |
+
'ASN1_GENERALIZEDTIME', 'PKCS7_ENC_CONTENT',
|
| 2663 |
+
'__darwin_pid_t', 'lldiv_t', 'comp_method_st',
|
| 2664 |
+
'EVP_MD_CTX', 'evp_cipher_st', 'X509_name_st',
|
| 2665 |
+
'x509_hash_dir_st', '__darwin_mach_port_name_t',
|
| 2666 |
+
'useconds_t', 'user_size_t', 'SSL_SESSION', 'rusage',
|
| 2667 |
+
'ssl_crock_st', 'int_least32_t', '__sigaction_u', 'dh_st',
|
| 2668 |
+
'P_ALL', '__darwin_stack_t', 'N6DES_ks3DOLLAR_9E',
|
| 2669 |
+
'comp_ctx_st', 'X509_CERT_FILE_CTX']
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/py2_test_grammar.py
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python test set -- part 1, grammar.
|
| 2 |
+
# This just tests whether the parser accepts them all.
|
| 3 |
+
|
| 4 |
+
# NOTE: When you run this test as a script from the command line, you
|
| 5 |
+
# get warnings about certain hex/oct constants. Since those are
|
| 6 |
+
# issued by the parser, you can't suppress them by adding a
|
| 7 |
+
# filterwarnings() call to this module. Therefore, to shut up the
|
| 8 |
+
# regression test, the filterwarnings() call has been added to
|
| 9 |
+
# regrtest.py.
|
| 10 |
+
|
| 11 |
+
from test.test_support import check_syntax_error
|
| 12 |
+
import unittest
|
| 13 |
+
import sys
|
| 14 |
+
# testing import *
|
| 15 |
+
from sys import *
|
| 16 |
+
|
| 17 |
+
class TokenTests(unittest.TestCase):
|
| 18 |
+
|
| 19 |
+
def testBackslash(self):
|
| 20 |
+
# Backslash means line continuation:
|
| 21 |
+
x = 1 \
|
| 22 |
+
+ 1
|
| 23 |
+
self.assertEquals(x, 2, 'backslash for line continuation')
|
| 24 |
+
|
| 25 |
+
# Backslash does not means continuation in comments :\
|
| 26 |
+
x = 0
|
| 27 |
+
self.assertEquals(x, 0, 'backslash ending comment')
|
| 28 |
+
|
| 29 |
+
def testPlainIntegers(self):
|
| 30 |
+
self.assertEquals(0xff, 255)
|
| 31 |
+
self.assertEquals(0377, 255)
|
| 32 |
+
self.assertEquals(2147483647, 017777777777)
|
| 33 |
+
# "0x" is not a valid literal
|
| 34 |
+
self.assertRaises(SyntaxError, eval, "0x")
|
| 35 |
+
from sys import maxint
|
| 36 |
+
if maxint == 2147483647:
|
| 37 |
+
self.assertEquals(-2147483647-1, -020000000000)
|
| 38 |
+
# XXX -2147483648
|
| 39 |
+
self.assert_(037777777777 > 0)
|
| 40 |
+
self.assert_(0xffffffff > 0)
|
| 41 |
+
for s in '2147483648', '040000000000', '0x100000000':
|
| 42 |
+
try:
|
| 43 |
+
x = eval(s)
|
| 44 |
+
except OverflowError:
|
| 45 |
+
self.fail("OverflowError on huge integer literal %r" % s)
|
| 46 |
+
elif maxint == 9223372036854775807:
|
| 47 |
+
self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
|
| 48 |
+
self.assert_(01777777777777777777777 > 0)
|
| 49 |
+
self.assert_(0xffffffffffffffff > 0)
|
| 50 |
+
for s in '9223372036854775808', '02000000000000000000000', \
|
| 51 |
+
'0x10000000000000000':
|
| 52 |
+
try:
|
| 53 |
+
x = eval(s)
|
| 54 |
+
except OverflowError:
|
| 55 |
+
self.fail("OverflowError on huge integer literal %r" % s)
|
| 56 |
+
else:
|
| 57 |
+
self.fail('Weird maxint value %r' % maxint)
|
| 58 |
+
|
| 59 |
+
def testLongIntegers(self):
|
| 60 |
+
x = 0L
|
| 61 |
+
x = 0l
|
| 62 |
+
x = 0xffffffffffffffffL
|
| 63 |
+
x = 0xffffffffffffffffl
|
| 64 |
+
x = 077777777777777777L
|
| 65 |
+
x = 077777777777777777l
|
| 66 |
+
x = 123456789012345678901234567890L
|
| 67 |
+
x = 123456789012345678901234567890l
|
| 68 |
+
|
| 69 |
+
def testFloats(self):
|
| 70 |
+
x = 3.14
|
| 71 |
+
x = 314.
|
| 72 |
+
x = 0.314
|
| 73 |
+
# XXX x = 000.314
|
| 74 |
+
x = .314
|
| 75 |
+
x = 3e14
|
| 76 |
+
x = 3E14
|
| 77 |
+
x = 3e-14
|
| 78 |
+
x = 3e+14
|
| 79 |
+
x = 3.e14
|
| 80 |
+
x = .3e14
|
| 81 |
+
x = 3.1e4
|
| 82 |
+
|
| 83 |
+
def testStringLiterals(self):
|
| 84 |
+
x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
|
| 85 |
+
x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
|
| 86 |
+
x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
|
| 87 |
+
x = "doesn't \"shrink\" does it"
|
| 88 |
+
y = 'doesn\'t "shrink" does it'
|
| 89 |
+
self.assert_(len(x) == 24 and x == y)
|
| 90 |
+
x = "does \"shrink\" doesn't it"
|
| 91 |
+
y = 'does "shrink" doesn\'t it'
|
| 92 |
+
self.assert_(len(x) == 24 and x == y)
|
| 93 |
+
x = """
|
| 94 |
+
The "quick"
|
| 95 |
+
brown fox
|
| 96 |
+
jumps over
|
| 97 |
+
the 'lazy' dog.
|
| 98 |
+
"""
|
| 99 |
+
y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
|
| 100 |
+
self.assertEquals(x, y)
|
| 101 |
+
y = '''
|
| 102 |
+
The "quick"
|
| 103 |
+
brown fox
|
| 104 |
+
jumps over
|
| 105 |
+
the 'lazy' dog.
|
| 106 |
+
'''
|
| 107 |
+
self.assertEquals(x, y)
|
| 108 |
+
y = "\n\
|
| 109 |
+
The \"quick\"\n\
|
| 110 |
+
brown fox\n\
|
| 111 |
+
jumps over\n\
|
| 112 |
+
the 'lazy' dog.\n\
|
| 113 |
+
"
|
| 114 |
+
self.assertEquals(x, y)
|
| 115 |
+
y = '\n\
|
| 116 |
+
The \"quick\"\n\
|
| 117 |
+
brown fox\n\
|
| 118 |
+
jumps over\n\
|
| 119 |
+
the \'lazy\' dog.\n\
|
| 120 |
+
'
|
| 121 |
+
self.assertEquals(x, y)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class GrammarTests(unittest.TestCase):
|
| 125 |
+
|
| 126 |
+
# single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
|
| 127 |
+
# XXX can't test in a script -- this rule is only used when interactive
|
| 128 |
+
|
| 129 |
+
# file_input: (NEWLINE | stmt)* ENDMARKER
|
| 130 |
+
# Being tested as this very moment this very module
|
| 131 |
+
|
| 132 |
+
# expr_input: testlist NEWLINE
|
| 133 |
+
# XXX Hard to test -- used only in calls to input()
|
| 134 |
+
|
| 135 |
+
def testEvalInput(self):
|
| 136 |
+
# testlist ENDMARKER
|
| 137 |
+
x = eval('1, 0 or 1')
|
| 138 |
+
|
| 139 |
+
def testFuncdef(self):
|
| 140 |
+
### 'def' NAME parameters ':' suite
|
| 141 |
+
### parameters: '(' [varargslist] ')'
|
| 142 |
+
### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
|
| 143 |
+
### | ('**'|'*' '*') NAME)
|
| 144 |
+
### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
|
| 145 |
+
### fpdef: NAME | '(' fplist ')'
|
| 146 |
+
### fplist: fpdef (',' fpdef)* [',']
|
| 147 |
+
### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
|
| 148 |
+
### argument: [test '='] test # Really [keyword '='] test
|
| 149 |
+
def f1(): pass
|
| 150 |
+
f1()
|
| 151 |
+
f1(*())
|
| 152 |
+
f1(*(), **{})
|
| 153 |
+
def f2(one_argument): pass
|
| 154 |
+
def f3(two, arguments): pass
|
| 155 |
+
def f4(two, (compound, (argument, list))): pass
|
| 156 |
+
def f5((compound, first), two): pass
|
| 157 |
+
self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
|
| 158 |
+
self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
|
| 159 |
+
if sys.platform.startswith('java'):
|
| 160 |
+
self.assertEquals(f4.func_code.co_varnames,
|
| 161 |
+
('two', '(compound, (argument, list))', 'compound', 'argument',
|
| 162 |
+
'list',))
|
| 163 |
+
self.assertEquals(f5.func_code.co_varnames,
|
| 164 |
+
('(compound, first)', 'two', 'compound', 'first'))
|
| 165 |
+
else:
|
| 166 |
+
self.assertEquals(f4.func_code.co_varnames,
|
| 167 |
+
('two', '.1', 'compound', 'argument', 'list'))
|
| 168 |
+
self.assertEquals(f5.func_code.co_varnames,
|
| 169 |
+
('.0', 'two', 'compound', 'first'))
|
| 170 |
+
def a1(one_arg,): pass
|
| 171 |
+
def a2(two, args,): pass
|
| 172 |
+
def v0(*rest): pass
|
| 173 |
+
def v1(a, *rest): pass
|
| 174 |
+
def v2(a, b, *rest): pass
|
| 175 |
+
def v3(a, (b, c), *rest): return a, b, c, rest
|
| 176 |
+
|
| 177 |
+
f1()
|
| 178 |
+
f2(1)
|
| 179 |
+
f2(1,)
|
| 180 |
+
f3(1, 2)
|
| 181 |
+
f3(1, 2,)
|
| 182 |
+
f4(1, (2, (3, 4)))
|
| 183 |
+
v0()
|
| 184 |
+
v0(1)
|
| 185 |
+
v0(1,)
|
| 186 |
+
v0(1,2)
|
| 187 |
+
v0(1,2,3,4,5,6,7,8,9,0)
|
| 188 |
+
v1(1)
|
| 189 |
+
v1(1,)
|
| 190 |
+
v1(1,2)
|
| 191 |
+
v1(1,2,3)
|
| 192 |
+
v1(1,2,3,4,5,6,7,8,9,0)
|
| 193 |
+
v2(1,2)
|
| 194 |
+
v2(1,2,3)
|
| 195 |
+
v2(1,2,3,4)
|
| 196 |
+
v2(1,2,3,4,5,6,7,8,9,0)
|
| 197 |
+
v3(1,(2,3))
|
| 198 |
+
v3(1,(2,3),4)
|
| 199 |
+
v3(1,(2,3),4,5,6,7,8,9,0)
|
| 200 |
+
|
| 201 |
+
# ceval unpacks the formal arguments into the first argcount names;
|
| 202 |
+
# thus, the names nested inside tuples must appear after these names.
|
| 203 |
+
if sys.platform.startswith('java'):
|
| 204 |
+
self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
|
| 205 |
+
else:
|
| 206 |
+
self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
|
| 207 |
+
self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
|
| 208 |
+
def d01(a=1): pass
|
| 209 |
+
d01()
|
| 210 |
+
d01(1)
|
| 211 |
+
d01(*(1,))
|
| 212 |
+
d01(**{'a':2})
|
| 213 |
+
def d11(a, b=1): pass
|
| 214 |
+
d11(1)
|
| 215 |
+
d11(1, 2)
|
| 216 |
+
d11(1, **{'b':2})
|
| 217 |
+
def d21(a, b, c=1): pass
|
| 218 |
+
d21(1, 2)
|
| 219 |
+
d21(1, 2, 3)
|
| 220 |
+
d21(*(1, 2, 3))
|
| 221 |
+
d21(1, *(2, 3))
|
| 222 |
+
d21(1, 2, *(3,))
|
| 223 |
+
d21(1, 2, **{'c':3})
|
| 224 |
+
def d02(a=1, b=2): pass
|
| 225 |
+
d02()
|
| 226 |
+
d02(1)
|
| 227 |
+
d02(1, 2)
|
| 228 |
+
d02(*(1, 2))
|
| 229 |
+
d02(1, *(2,))
|
| 230 |
+
d02(1, **{'b':2})
|
| 231 |
+
d02(**{'a': 1, 'b': 2})
|
| 232 |
+
def d12(a, b=1, c=2): pass
|
| 233 |
+
d12(1)
|
| 234 |
+
d12(1, 2)
|
| 235 |
+
d12(1, 2, 3)
|
| 236 |
+
def d22(a, b, c=1, d=2): pass
|
| 237 |
+
d22(1, 2)
|
| 238 |
+
d22(1, 2, 3)
|
| 239 |
+
d22(1, 2, 3, 4)
|
| 240 |
+
def d01v(a=1, *rest): pass
|
| 241 |
+
d01v()
|
| 242 |
+
d01v(1)
|
| 243 |
+
d01v(1, 2)
|
| 244 |
+
d01v(*(1, 2, 3, 4))
|
| 245 |
+
d01v(*(1,))
|
| 246 |
+
d01v(**{'a':2})
|
| 247 |
+
def d11v(a, b=1, *rest): pass
|
| 248 |
+
d11v(1)
|
| 249 |
+
d11v(1, 2)
|
| 250 |
+
d11v(1, 2, 3)
|
| 251 |
+
def d21v(a, b, c=1, *rest): pass
|
| 252 |
+
d21v(1, 2)
|
| 253 |
+
d21v(1, 2, 3)
|
| 254 |
+
d21v(1, 2, 3, 4)
|
| 255 |
+
d21v(*(1, 2, 3, 4))
|
| 256 |
+
d21v(1, 2, **{'c': 3})
|
| 257 |
+
def d02v(a=1, b=2, *rest): pass
|
| 258 |
+
d02v()
|
| 259 |
+
d02v(1)
|
| 260 |
+
d02v(1, 2)
|
| 261 |
+
d02v(1, 2, 3)
|
| 262 |
+
d02v(1, *(2, 3, 4))
|
| 263 |
+
d02v(**{'a': 1, 'b': 2})
|
| 264 |
+
def d12v(a, b=1, c=2, *rest): pass
|
| 265 |
+
d12v(1)
|
| 266 |
+
d12v(1, 2)
|
| 267 |
+
d12v(1, 2, 3)
|
| 268 |
+
d12v(1, 2, 3, 4)
|
| 269 |
+
d12v(*(1, 2, 3, 4))
|
| 270 |
+
d12v(1, 2, *(3, 4, 5))
|
| 271 |
+
d12v(1, *(2,), **{'c': 3})
|
| 272 |
+
def d22v(a, b, c=1, d=2, *rest): pass
|
| 273 |
+
d22v(1, 2)
|
| 274 |
+
d22v(1, 2, 3)
|
| 275 |
+
d22v(1, 2, 3, 4)
|
| 276 |
+
d22v(1, 2, 3, 4, 5)
|
| 277 |
+
d22v(*(1, 2, 3, 4))
|
| 278 |
+
d22v(1, 2, *(3, 4, 5))
|
| 279 |
+
d22v(1, *(2, 3), **{'d': 4})
|
| 280 |
+
def d31v((x)): pass
|
| 281 |
+
d31v(1)
|
| 282 |
+
def d32v((x,)): pass
|
| 283 |
+
d32v((1,))
|
| 284 |
+
|
| 285 |
+
# keyword arguments after *arglist
|
| 286 |
+
def f(*args, **kwargs):
|
| 287 |
+
return args, kwargs
|
| 288 |
+
self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
|
| 289 |
+
{'x':2, 'y':5}))
|
| 290 |
+
self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
|
| 291 |
+
self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
|
| 292 |
+
|
| 293 |
+
# Check ast errors in *args and *kwargs
|
| 294 |
+
check_syntax_error(self, "f(*g(1=2))")
|
| 295 |
+
check_syntax_error(self, "f(**g(1=2))")
|
| 296 |
+
|
| 297 |
+
def testLambdef(self):
|
| 298 |
+
### lambdef: 'lambda' [varargslist] ':' test
|
| 299 |
+
l1 = lambda : 0
|
| 300 |
+
self.assertEquals(l1(), 0)
|
| 301 |
+
l2 = lambda : a[d] # XXX just testing the expression
|
| 302 |
+
l3 = lambda : [2 < x for x in [-1, 3, 0L]]
|
| 303 |
+
self.assertEquals(l3(), [0, 1, 0])
|
| 304 |
+
l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
|
| 305 |
+
self.assertEquals(l4(), 1)
|
| 306 |
+
l5 = lambda x, y, z=2: x + y + z
|
| 307 |
+
self.assertEquals(l5(1, 2), 5)
|
| 308 |
+
self.assertEquals(l5(1, 2, 3), 6)
|
| 309 |
+
check_syntax_error(self, "lambda x: x = 2")
|
| 310 |
+
check_syntax_error(self, "lambda (None,): None")
|
| 311 |
+
|
| 312 |
+
### stmt: simple_stmt | compound_stmt
|
| 313 |
+
# Tested below
|
| 314 |
+
|
| 315 |
+
def testSimpleStmt(self):
|
| 316 |
+
### simple_stmt: small_stmt (';' small_stmt)* [';']
|
| 317 |
+
x = 1; pass; del x
|
| 318 |
+
def foo():
|
| 319 |
+
# verify statements that end with semi-colons
|
| 320 |
+
x = 1; pass; del x;
|
| 321 |
+
foo()
|
| 322 |
+
|
| 323 |
+
### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
|
| 324 |
+
# Tested below
|
| 325 |
+
|
| 326 |
+
def testExprStmt(self):
|
| 327 |
+
# (exprlist '=')* exprlist
|
| 328 |
+
1
|
| 329 |
+
1, 2, 3
|
| 330 |
+
x = 1
|
| 331 |
+
x = 1, 2, 3
|
| 332 |
+
x = y = z = 1, 2, 3
|
| 333 |
+
x, y, z = 1, 2, 3
|
| 334 |
+
abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
|
| 335 |
+
|
| 336 |
+
check_syntax_error(self, "x + 1 = 1")
|
| 337 |
+
check_syntax_error(self, "a + 1 = b + 2")
|
| 338 |
+
|
| 339 |
+
def testPrintStmt(self):
|
| 340 |
+
# 'print' (test ',')* [test]
|
| 341 |
+
import StringIO
|
| 342 |
+
|
| 343 |
+
# Can't test printing to real stdout without comparing output
|
| 344 |
+
# which is not available in unittest.
|
| 345 |
+
save_stdout = sys.stdout
|
| 346 |
+
sys.stdout = StringIO.StringIO()
|
| 347 |
+
|
| 348 |
+
print 1, 2, 3
|
| 349 |
+
print 1, 2, 3,
|
| 350 |
+
print
|
| 351 |
+
print 0 or 1, 0 or 1,
|
| 352 |
+
print 0 or 1
|
| 353 |
+
|
| 354 |
+
# 'print' '>>' test ','
|
| 355 |
+
print >> sys.stdout, 1, 2, 3
|
| 356 |
+
print >> sys.stdout, 1, 2, 3,
|
| 357 |
+
print >> sys.stdout
|
| 358 |
+
print >> sys.stdout, 0 or 1, 0 or 1,
|
| 359 |
+
print >> sys.stdout, 0 or 1
|
| 360 |
+
|
| 361 |
+
# test printing to an instance
|
| 362 |
+
class Gulp:
|
| 363 |
+
def write(self, msg): pass
|
| 364 |
+
|
| 365 |
+
gulp = Gulp()
|
| 366 |
+
print >> gulp, 1, 2, 3
|
| 367 |
+
print >> gulp, 1, 2, 3,
|
| 368 |
+
print >> gulp
|
| 369 |
+
print >> gulp, 0 or 1, 0 or 1,
|
| 370 |
+
print >> gulp, 0 or 1
|
| 371 |
+
|
| 372 |
+
# test print >> None
|
| 373 |
+
def driver():
|
| 374 |
+
oldstdout = sys.stdout
|
| 375 |
+
sys.stdout = Gulp()
|
| 376 |
+
try:
|
| 377 |
+
tellme(Gulp())
|
| 378 |
+
tellme()
|
| 379 |
+
finally:
|
| 380 |
+
sys.stdout = oldstdout
|
| 381 |
+
|
| 382 |
+
# we should see this once
|
| 383 |
+
def tellme(file=sys.stdout):
|
| 384 |
+
print >> file, 'hello world'
|
| 385 |
+
|
| 386 |
+
driver()
|
| 387 |
+
|
| 388 |
+
# we should not see this at all
|
| 389 |
+
def tellme(file=None):
|
| 390 |
+
print >> file, 'goodbye universe'
|
| 391 |
+
|
| 392 |
+
driver()
|
| 393 |
+
|
| 394 |
+
self.assertEqual(sys.stdout.getvalue(), '''\
|
| 395 |
+
1 2 3
|
| 396 |
+
1 2 3
|
| 397 |
+
1 1 1
|
| 398 |
+
1 2 3
|
| 399 |
+
1 2 3
|
| 400 |
+
1 1 1
|
| 401 |
+
hello world
|
| 402 |
+
''')
|
| 403 |
+
sys.stdout = save_stdout
|
| 404 |
+
|
| 405 |
+
# syntax errors
|
| 406 |
+
check_syntax_error(self, 'print ,')
|
| 407 |
+
check_syntax_error(self, 'print >> x,')
|
| 408 |
+
|
| 409 |
+
def testDelStmt(self):
|
| 410 |
+
# 'del' exprlist
|
| 411 |
+
abc = [1,2,3]
|
| 412 |
+
x, y, z = abc
|
| 413 |
+
xyz = x, y, z
|
| 414 |
+
|
| 415 |
+
del abc
|
| 416 |
+
del x, y, (z, xyz)
|
| 417 |
+
|
| 418 |
+
def testPassStmt(self):
|
| 419 |
+
# 'pass'
|
| 420 |
+
pass
|
| 421 |
+
|
| 422 |
+
# flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
|
| 423 |
+
# Tested below
|
| 424 |
+
|
| 425 |
+
def testBreakStmt(self):
|
| 426 |
+
# 'break'
|
| 427 |
+
while 1: break
|
| 428 |
+
|
| 429 |
+
def testContinueStmt(self):
|
| 430 |
+
# 'continue'
|
| 431 |
+
i = 1
|
| 432 |
+
while i: i = 0; continue
|
| 433 |
+
|
| 434 |
+
msg = ""
|
| 435 |
+
while not msg:
|
| 436 |
+
msg = "ok"
|
| 437 |
+
try:
|
| 438 |
+
continue
|
| 439 |
+
msg = "continue failed to continue inside try"
|
| 440 |
+
except:
|
| 441 |
+
msg = "continue inside try called except block"
|
| 442 |
+
if msg != "ok":
|
| 443 |
+
self.fail(msg)
|
| 444 |
+
|
| 445 |
+
msg = ""
|
| 446 |
+
while not msg:
|
| 447 |
+
msg = "finally block not called"
|
| 448 |
+
try:
|
| 449 |
+
continue
|
| 450 |
+
finally:
|
| 451 |
+
msg = "ok"
|
| 452 |
+
if msg != "ok":
|
| 453 |
+
self.fail(msg)
|
| 454 |
+
|
| 455 |
+
def test_break_continue_loop(self):
|
| 456 |
+
# This test warrants an explanation. It is a test specifically for SF bugs
|
| 457 |
+
# #463359 and #462937. The bug is that a 'break' statement executed or
|
| 458 |
+
# exception raised inside a try/except inside a loop, *after* a continue
|
| 459 |
+
# statement has been executed in that loop, will cause the wrong number of
|
| 460 |
+
# arguments to be popped off the stack and the instruction pointer reset to
|
| 461 |
+
# a very small number (usually 0.) Because of this, the following test
|
| 462 |
+
# *must* written as a function, and the tracking vars *must* be function
|
| 463 |
+
# arguments with default values. Otherwise, the test will loop and loop.
|
| 464 |
+
|
| 465 |
+
def test_inner(extra_burning_oil = 1, count=0):
|
| 466 |
+
big_hippo = 2
|
| 467 |
+
while big_hippo:
|
| 468 |
+
count += 1
|
| 469 |
+
try:
|
| 470 |
+
if extra_burning_oil and big_hippo == 1:
|
| 471 |
+
extra_burning_oil -= 1
|
| 472 |
+
break
|
| 473 |
+
big_hippo -= 1
|
| 474 |
+
continue
|
| 475 |
+
except:
|
| 476 |
+
raise
|
| 477 |
+
if count > 2 or big_hippo <> 1:
|
| 478 |
+
self.fail("continue then break in try/except in loop broken!")
|
| 479 |
+
test_inner()
|
| 480 |
+
|
| 481 |
+
def testReturn(self):
|
| 482 |
+
# 'return' [testlist]
|
| 483 |
+
def g1(): return
|
| 484 |
+
def g2(): return 1
|
| 485 |
+
g1()
|
| 486 |
+
x = g2()
|
| 487 |
+
check_syntax_error(self, "class foo:return 1")
|
| 488 |
+
|
| 489 |
+
def testYield(self):
|
| 490 |
+
check_syntax_error(self, "class foo:yield 1")
|
| 491 |
+
|
| 492 |
+
def testRaise(self):
|
| 493 |
+
# 'raise' test [',' test]
|
| 494 |
+
try: raise RuntimeError, 'just testing'
|
| 495 |
+
except RuntimeError: pass
|
| 496 |
+
try: raise KeyboardInterrupt
|
| 497 |
+
except KeyboardInterrupt: pass
|
| 498 |
+
|
| 499 |
+
def testImport(self):
|
| 500 |
+
# 'import' dotted_as_names
|
| 501 |
+
import sys
|
| 502 |
+
import time, sys
|
| 503 |
+
# 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
|
| 504 |
+
from time import time
|
| 505 |
+
from time import (time)
|
| 506 |
+
# not testable inside a function, but already done at top of the module
|
| 507 |
+
# from sys import *
|
| 508 |
+
from sys import path, argv
|
| 509 |
+
from sys import (path, argv)
|
| 510 |
+
from sys import (path, argv,)
|
| 511 |
+
|
| 512 |
+
def testGlobal(self):
|
| 513 |
+
# 'global' NAME (',' NAME)*
|
| 514 |
+
global a
|
| 515 |
+
global a, b
|
| 516 |
+
global one, two, three, four, five, six, seven, eight, nine, ten
|
| 517 |
+
|
| 518 |
+
def testExec(self):
|
| 519 |
+
# 'exec' expr ['in' expr [',' expr]]
|
| 520 |
+
z = None
|
| 521 |
+
del z
|
| 522 |
+
exec 'z=1+1\n'
|
| 523 |
+
if z != 2: self.fail('exec \'z=1+1\'\\n')
|
| 524 |
+
del z
|
| 525 |
+
exec 'z=1+1'
|
| 526 |
+
if z != 2: self.fail('exec \'z=1+1\'')
|
| 527 |
+
z = None
|
| 528 |
+
del z
|
| 529 |
+
import types
|
| 530 |
+
if hasattr(types, "UnicodeType"):
|
| 531 |
+
exec r"""if 1:
|
| 532 |
+
exec u'z=1+1\n'
|
| 533 |
+
if z != 2: self.fail('exec u\'z=1+1\'\\n')
|
| 534 |
+
del z
|
| 535 |
+
exec u'z=1+1'
|
| 536 |
+
if z != 2: self.fail('exec u\'z=1+1\'')"""
|
| 537 |
+
g = {}
|
| 538 |
+
exec 'z = 1' in g
|
| 539 |
+
if g.has_key('__builtins__'): del g['__builtins__']
|
| 540 |
+
if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
|
| 541 |
+
g = {}
|
| 542 |
+
l = {}
|
| 543 |
+
|
| 544 |
+
import warnings
|
| 545 |
+
warnings.filterwarnings("ignore", "global statement", module="<string>")
|
| 546 |
+
exec 'global a; a = 1; b = 2' in g, l
|
| 547 |
+
if g.has_key('__builtins__'): del g['__builtins__']
|
| 548 |
+
if l.has_key('__builtins__'): del l['__builtins__']
|
| 549 |
+
if (g, l) != ({'a':1}, {'b':2}):
|
| 550 |
+
self.fail('exec ... in g (%s), l (%s)' %(g,l))
|
| 551 |
+
|
| 552 |
+
def testAssert(self):
|
| 553 |
+
# assert_stmt: 'assert' test [',' test]
|
| 554 |
+
assert 1
|
| 555 |
+
assert 1, 1
|
| 556 |
+
assert lambda x:x
|
| 557 |
+
assert 1, lambda x:x+1
|
| 558 |
+
try:
|
| 559 |
+
assert 0, "msg"
|
| 560 |
+
except AssertionError, e:
|
| 561 |
+
self.assertEquals(e.args[0], "msg")
|
| 562 |
+
else:
|
| 563 |
+
if __debug__:
|
| 564 |
+
self.fail("AssertionError not raised by assert 0")
|
| 565 |
+
|
| 566 |
+
### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
|
| 567 |
+
# Tested below
|
| 568 |
+
|
| 569 |
+
def testIf(self):
|
| 570 |
+
# 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
|
| 571 |
+
if 1: pass
|
| 572 |
+
if 1: pass
|
| 573 |
+
else: pass
|
| 574 |
+
if 0: pass
|
| 575 |
+
elif 0: pass
|
| 576 |
+
if 0: pass
|
| 577 |
+
elif 0: pass
|
| 578 |
+
elif 0: pass
|
| 579 |
+
elif 0: pass
|
| 580 |
+
else: pass
|
| 581 |
+
|
| 582 |
+
def testWhile(self):
|
| 583 |
+
# 'while' test ':' suite ['else' ':' suite]
|
| 584 |
+
while 0: pass
|
| 585 |
+
while 0: pass
|
| 586 |
+
else: pass
|
| 587 |
+
|
| 588 |
+
# Issue1920: "while 0" is optimized away,
|
| 589 |
+
# ensure that the "else" clause is still present.
|
| 590 |
+
x = 0
|
| 591 |
+
while 0:
|
| 592 |
+
x = 1
|
| 593 |
+
else:
|
| 594 |
+
x = 2
|
| 595 |
+
self.assertEquals(x, 2)
|
| 596 |
+
|
| 597 |
+
def testFor(self):
|
| 598 |
+
# 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
|
| 599 |
+
for i in 1, 2, 3: pass
|
| 600 |
+
for i, j, k in (): pass
|
| 601 |
+
else: pass
|
| 602 |
+
class Squares:
|
| 603 |
+
def __init__(self, max):
|
| 604 |
+
self.max = max
|
| 605 |
+
self.sofar = []
|
| 606 |
+
def __len__(self): return len(self.sofar)
|
| 607 |
+
def __getitem__(self, i):
|
| 608 |
+
if not 0 <= i < self.max: raise IndexError
|
| 609 |
+
n = len(self.sofar)
|
| 610 |
+
while n <= i:
|
| 611 |
+
self.sofar.append(n*n)
|
| 612 |
+
n = n+1
|
| 613 |
+
return self.sofar[i]
|
| 614 |
+
n = 0
|
| 615 |
+
for x in Squares(10): n = n+x
|
| 616 |
+
if n != 285:
|
| 617 |
+
self.fail('for over growing sequence')
|
| 618 |
+
|
| 619 |
+
result = []
|
| 620 |
+
for x, in [(1,), (2,), (3,)]:
|
| 621 |
+
result.append(x)
|
| 622 |
+
self.assertEqual(result, [1, 2, 3])
|
| 623 |
+
|
| 624 |
+
def testTry(self):
|
| 625 |
+
### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
|
| 626 |
+
### | 'try' ':' suite 'finally' ':' suite
|
| 627 |
+
### except_clause: 'except' [expr [('as' | ',') expr]]
|
| 628 |
+
try:
|
| 629 |
+
1/0
|
| 630 |
+
except ZeroDivisionError:
|
| 631 |
+
pass
|
| 632 |
+
else:
|
| 633 |
+
pass
|
| 634 |
+
try: 1/0
|
| 635 |
+
except EOFError: pass
|
| 636 |
+
except TypeError as msg: pass
|
| 637 |
+
except RuntimeError, msg: pass
|
| 638 |
+
except: pass
|
| 639 |
+
else: pass
|
| 640 |
+
try: 1/0
|
| 641 |
+
except (EOFError, TypeError, ZeroDivisionError): pass
|
| 642 |
+
try: 1/0
|
| 643 |
+
except (EOFError, TypeError, ZeroDivisionError), msg: pass
|
| 644 |
+
try: pass
|
| 645 |
+
finally: pass
|
| 646 |
+
|
| 647 |
+
def testSuite(self):
|
| 648 |
+
# simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
|
| 649 |
+
if 1: pass
|
| 650 |
+
if 1:
|
| 651 |
+
pass
|
| 652 |
+
if 1:
|
| 653 |
+
#
|
| 654 |
+
#
|
| 655 |
+
#
|
| 656 |
+
pass
|
| 657 |
+
pass
|
| 658 |
+
#
|
| 659 |
+
pass
|
| 660 |
+
#
|
| 661 |
+
|
| 662 |
+
def testTest(self):
|
| 663 |
+
### and_test ('or' and_test)*
|
| 664 |
+
### and_test: not_test ('and' not_test)*
|
| 665 |
+
### not_test: 'not' not_test | comparison
|
| 666 |
+
if not 1: pass
|
| 667 |
+
if 1 and 1: pass
|
| 668 |
+
if 1 or 1: pass
|
| 669 |
+
if not not not 1: pass
|
| 670 |
+
if not 1 and 1 and 1: pass
|
| 671 |
+
if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
|
| 672 |
+
|
| 673 |
+
def testComparison(self):
|
| 674 |
+
### comparison: expr (comp_op expr)*
|
| 675 |
+
### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
|
| 676 |
+
if 1: pass
|
| 677 |
+
x = (1 == 1)
|
| 678 |
+
if 1 == 1: pass
|
| 679 |
+
if 1 != 1: pass
|
| 680 |
+
if 1 <> 1: pass
|
| 681 |
+
if 1 < 1: pass
|
| 682 |
+
if 1 > 1: pass
|
| 683 |
+
if 1 <= 1: pass
|
| 684 |
+
if 1 >= 1: pass
|
| 685 |
+
if 1 is 1: pass
|
| 686 |
+
if 1 is not 1: pass
|
| 687 |
+
if 1 in (): pass
|
| 688 |
+
if 1 not in (): pass
|
| 689 |
+
if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
|
| 690 |
+
|
| 691 |
+
def testBinaryMaskOps(self):
|
| 692 |
+
x = 1 & 1
|
| 693 |
+
x = 1 ^ 1
|
| 694 |
+
x = 1 | 1
|
| 695 |
+
|
| 696 |
+
def testShiftOps(self):
|
| 697 |
+
x = 1 << 1
|
| 698 |
+
x = 1 >> 1
|
| 699 |
+
x = 1 << 1 >> 1
|
| 700 |
+
|
| 701 |
+
def testAdditiveOps(self):
|
| 702 |
+
x = 1
|
| 703 |
+
x = 1 + 1
|
| 704 |
+
x = 1 - 1 - 1
|
| 705 |
+
x = 1 - 1 + 1 - 1 + 1
|
| 706 |
+
|
| 707 |
+
def testMultiplicativeOps(self):
|
| 708 |
+
x = 1 * 1
|
| 709 |
+
x = 1 / 1
|
| 710 |
+
x = 1 % 1
|
| 711 |
+
x = 1 / 1 * 1 % 1
|
| 712 |
+
|
| 713 |
+
def testUnaryOps(self):
|
| 714 |
+
x = +1
|
| 715 |
+
x = -1
|
| 716 |
+
x = ~1
|
| 717 |
+
x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
|
| 718 |
+
x = -1*1/1 + 1*1 - ---1*1
|
| 719 |
+
|
| 720 |
+
def testSelectors(self):
|
| 721 |
+
### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
|
| 722 |
+
### subscript: expr | [expr] ':' [expr]
|
| 723 |
+
|
| 724 |
+
import sys, time
|
| 725 |
+
c = sys.path[0]
|
| 726 |
+
x = time.time()
|
| 727 |
+
x = sys.modules['time'].time()
|
| 728 |
+
a = '01234'
|
| 729 |
+
c = a[0]
|
| 730 |
+
c = a[-1]
|
| 731 |
+
s = a[0:5]
|
| 732 |
+
s = a[:5]
|
| 733 |
+
s = a[0:]
|
| 734 |
+
s = a[:]
|
| 735 |
+
s = a[-5:]
|
| 736 |
+
s = a[:-1]
|
| 737 |
+
s = a[-4:-3]
|
| 738 |
+
# A rough test of SF bug 1333982. https://python.org/sf/1333982
|
| 739 |
+
# The testing here is fairly incomplete.
|
| 740 |
+
# Test cases should include: commas with 1 and 2 colons
|
| 741 |
+
d = {}
|
| 742 |
+
d[1] = 1
|
| 743 |
+
d[1,] = 2
|
| 744 |
+
d[1,2] = 3
|
| 745 |
+
d[1,2,3] = 4
|
| 746 |
+
L = list(d)
|
| 747 |
+
L.sort()
|
| 748 |
+
self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
|
| 749 |
+
|
| 750 |
+
def testAtoms(self):
|
| 751 |
+
### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
|
| 752 |
+
### dictmaker: test ':' test (',' test ':' test)* [',']
|
| 753 |
+
|
| 754 |
+
x = (1)
|
| 755 |
+
x = (1 or 2 or 3)
|
| 756 |
+
x = (1 or 2 or 3, 2, 3)
|
| 757 |
+
|
| 758 |
+
x = []
|
| 759 |
+
x = [1]
|
| 760 |
+
x = [1 or 2 or 3]
|
| 761 |
+
x = [1 or 2 or 3, 2, 3]
|
| 762 |
+
x = []
|
| 763 |
+
|
| 764 |
+
x = {}
|
| 765 |
+
x = {'one': 1}
|
| 766 |
+
x = {'one': 1,}
|
| 767 |
+
x = {'one' or 'two': 1 or 2}
|
| 768 |
+
x = {'one': 1, 'two': 2}
|
| 769 |
+
x = {'one': 1, 'two': 2,}
|
| 770 |
+
x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
|
| 771 |
+
|
| 772 |
+
x = `x`
|
| 773 |
+
x = `1 or 2 or 3`
|
| 774 |
+
self.assertEqual(`1,2`, '(1, 2)')
|
| 775 |
+
|
| 776 |
+
x = x
|
| 777 |
+
x = 'x'
|
| 778 |
+
x = 123
|
| 779 |
+
|
| 780 |
+
### exprlist: expr (',' expr)* [',']
|
| 781 |
+
### testlist: test (',' test)* [',']
|
| 782 |
+
# These have been exercised enough above
|
| 783 |
+
|
| 784 |
+
def testClassdef(self):
|
| 785 |
+
# 'class' NAME ['(' [testlist] ')'] ':' suite
|
| 786 |
+
class B: pass
|
| 787 |
+
class B2(): pass
|
| 788 |
+
class C1(B): pass
|
| 789 |
+
class C2(B): pass
|
| 790 |
+
class D(C1, C2, B): pass
|
| 791 |
+
class C:
|
| 792 |
+
def meth1(self): pass
|
| 793 |
+
def meth2(self, arg): pass
|
| 794 |
+
def meth3(self, a1, a2): pass
|
| 795 |
+
# decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
|
| 796 |
+
# decorators: decorator+
|
| 797 |
+
# decorated: decorators (classdef | funcdef)
|
| 798 |
+
def class_decorator(x):
|
| 799 |
+
x.decorated = True
|
| 800 |
+
return x
|
| 801 |
+
@class_decorator
|
| 802 |
+
class G:
|
| 803 |
+
pass
|
| 804 |
+
self.assertEqual(G.decorated, True)
|
| 805 |
+
|
| 806 |
+
def testListcomps(self):
|
| 807 |
+
# list comprehension tests
|
| 808 |
+
nums = [1, 2, 3, 4, 5]
|
| 809 |
+
strs = ["Apple", "Banana", "Coconut"]
|
| 810 |
+
spcs = [" Apple", " Banana ", "Coco nut "]
|
| 811 |
+
|
| 812 |
+
self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
|
| 813 |
+
self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
|
| 814 |
+
self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
|
| 815 |
+
self.assertEqual([(i, s) for i in nums for s in strs],
|
| 816 |
+
[(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
|
| 817 |
+
(2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
|
| 818 |
+
(3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
|
| 819 |
+
(4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
|
| 820 |
+
(5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
|
| 821 |
+
self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
|
| 822 |
+
[(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
|
| 823 |
+
(3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
|
| 824 |
+
(5, 'Banana'), (5, 'Coconut')])
|
| 825 |
+
self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
|
| 826 |
+
[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
|
| 827 |
+
|
| 828 |
+
def test_in_func(l):
|
| 829 |
+
return [None < x < 3 for x in l if x > 2]
|
| 830 |
+
|
| 831 |
+
self.assertEqual(test_in_func(nums), [False, False, False])
|
| 832 |
+
|
| 833 |
+
def test_nested_front():
|
| 834 |
+
self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
|
| 835 |
+
[[1, 2], [3, 4], [5, 6]])
|
| 836 |
+
|
| 837 |
+
test_nested_front()
|
| 838 |
+
|
| 839 |
+
check_syntax_error(self, "[i, s for i in nums for s in strs]")
|
| 840 |
+
check_syntax_error(self, "[x if y]")
|
| 841 |
+
|
| 842 |
+
suppliers = [
|
| 843 |
+
(1, "Boeing"),
|
| 844 |
+
(2, "Ford"),
|
| 845 |
+
(3, "Macdonalds")
|
| 846 |
+
]
|
| 847 |
+
|
| 848 |
+
parts = [
|
| 849 |
+
(10, "Airliner"),
|
| 850 |
+
(20, "Engine"),
|
| 851 |
+
(30, "Cheeseburger")
|
| 852 |
+
]
|
| 853 |
+
|
| 854 |
+
suppart = [
|
| 855 |
+
(1, 10), (1, 20), (2, 20), (3, 30)
|
| 856 |
+
]
|
| 857 |
+
|
| 858 |
+
x = [
|
| 859 |
+
(sname, pname)
|
| 860 |
+
for (sno, sname) in suppliers
|
| 861 |
+
for (pno, pname) in parts
|
| 862 |
+
for (sp_sno, sp_pno) in suppart
|
| 863 |
+
if sno == sp_sno and pno == sp_pno
|
| 864 |
+
]
|
| 865 |
+
|
| 866 |
+
self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
|
| 867 |
+
('Macdonalds', 'Cheeseburger')])
|
| 868 |
+
|
| 869 |
+
def testGenexps(self):
|
| 870 |
+
# generator expression tests
|
| 871 |
+
g = ([x for x in range(10)] for x in range(1))
|
| 872 |
+
self.assertEqual(g.next(), [x for x in range(10)])
|
| 873 |
+
try:
|
| 874 |
+
g.next()
|
| 875 |
+
self.fail('should produce StopIteration exception')
|
| 876 |
+
except StopIteration:
|
| 877 |
+
pass
|
| 878 |
+
|
| 879 |
+
a = 1
|
| 880 |
+
try:
|
| 881 |
+
g = (a for d in a)
|
| 882 |
+
g.next()
|
| 883 |
+
self.fail('should produce TypeError')
|
| 884 |
+
except TypeError:
|
| 885 |
+
pass
|
| 886 |
+
|
| 887 |
+
self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
|
| 888 |
+
self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
|
| 889 |
+
|
| 890 |
+
a = [x for x in range(10)]
|
| 891 |
+
b = (x for x in (y for y in a))
|
| 892 |
+
self.assertEqual(sum(b), sum([x for x in range(10)]))
|
| 893 |
+
|
| 894 |
+
self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
|
| 895 |
+
self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
|
| 896 |
+
self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
|
| 897 |
+
self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
|
| 898 |
+
self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
|
| 899 |
+
self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
|
| 900 |
+
self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
|
| 901 |
+
check_syntax_error(self, "foo(x for x in range(10), 100)")
|
| 902 |
+
check_syntax_error(self, "foo(100, x for x in range(10))")
|
| 903 |
+
|
| 904 |
+
def testComprehensionSpecials(self):
|
| 905 |
+
# test for outmost iterable precomputation
|
| 906 |
+
x = 10; g = (i for i in range(x)); x = 5
|
| 907 |
+
self.assertEqual(len(list(g)), 10)
|
| 908 |
+
|
| 909 |
+
# This should hold, since we're only precomputing outmost iterable.
|
| 910 |
+
x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
|
| 911 |
+
x = 5; t = True;
|
| 912 |
+
self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
|
| 913 |
+
|
| 914 |
+
# Grammar allows multiple adjacent 'if's in listcomps and genexps,
|
| 915 |
+
# even though it's silly. Make sure it works (ifelse broke this.)
|
| 916 |
+
self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
|
| 917 |
+
self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
|
| 918 |
+
|
| 919 |
+
# verify unpacking single element tuples in listcomp/genexp.
|
| 920 |
+
self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
|
| 921 |
+
self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
|
| 922 |
+
|
| 923 |
+
def test_with_statement(self):
|
| 924 |
+
class manager(object):
|
| 925 |
+
def __enter__(self):
|
| 926 |
+
return (1, 2)
|
| 927 |
+
def __exit__(self, *args):
|
| 928 |
+
pass
|
| 929 |
+
|
| 930 |
+
with manager():
|
| 931 |
+
pass
|
| 932 |
+
with manager() as x:
|
| 933 |
+
pass
|
| 934 |
+
with manager() as (x, y):
|
| 935 |
+
pass
|
| 936 |
+
with manager(), manager():
|
| 937 |
+
pass
|
| 938 |
+
with manager() as x, manager() as y:
|
| 939 |
+
pass
|
| 940 |
+
with manager() as x, manager():
|
| 941 |
+
pass
|
| 942 |
+
|
| 943 |
+
def testIfElseExpr(self):
|
| 944 |
+
# Test ifelse expressions in various cases
|
| 945 |
+
def _checkeval(msg, ret):
|
| 946 |
+
"helper to check that evaluation of expressions is done correctly"
|
| 947 |
+
print x
|
| 948 |
+
return ret
|
| 949 |
+
|
| 950 |
+
self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
|
| 951 |
+
self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
|
| 952 |
+
self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
|
| 953 |
+
self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
|
| 954 |
+
self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
|
| 955 |
+
self.assertEqual((5 and 6 if 0 else 1), 1)
|
| 956 |
+
self.assertEqual(((5 and 6) if 0 else 1), 1)
|
| 957 |
+
self.assertEqual((5 and (6 if 1 else 1)), 6)
|
| 958 |
+
self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
|
| 959 |
+
self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
|
| 960 |
+
self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
|
| 961 |
+
self.assertEqual((not 5 if 1 else 1), False)
|
| 962 |
+
self.assertEqual((not 5 if 0 else 1), 1)
|
| 963 |
+
self.assertEqual((6 + 1 if 1 else 2), 7)
|
| 964 |
+
self.assertEqual((6 - 1 if 1 else 2), 5)
|
| 965 |
+
self.assertEqual((6 * 2 if 1 else 4), 12)
|
| 966 |
+
self.assertEqual((6 / 2 if 1 else 3), 3)
|
| 967 |
+
self.assertEqual((6 < 4 if 0 else 2), 2)
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
if __name__ == '__main__':
|
| 971 |
+
unittest.main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/data/py3_test_grammar.py
ADDED
|
@@ -0,0 +1,956 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python test set -- part 1, grammar.
|
| 2 |
+
# This just tests whether the parser accepts them all.
|
| 3 |
+
|
| 4 |
+
# NOTE: When you run this test as a script from the command line, you
|
| 5 |
+
# get warnings about certain hex/oct constants. Since those are
|
| 6 |
+
# issued by the parser, you can't suppress them by adding a
|
| 7 |
+
# filterwarnings() call to this module. Therefore, to shut up the
|
| 8 |
+
# regression test, the filterwarnings() call has been added to
|
| 9 |
+
# regrtest.py.
|
| 10 |
+
|
| 11 |
+
from test.support import check_syntax_error
|
| 12 |
+
import unittest
|
| 13 |
+
import sys
|
| 14 |
+
# testing import *
|
| 15 |
+
from sys import *
|
| 16 |
+
|
| 17 |
+
class TokenTests(unittest.TestCase):
|
| 18 |
+
|
| 19 |
+
def testBackslash(self):
|
| 20 |
+
# Backslash means line continuation:
|
| 21 |
+
x = 1 \
|
| 22 |
+
+ 1
|
| 23 |
+
self.assertEquals(x, 2, 'backslash for line continuation')
|
| 24 |
+
|
| 25 |
+
# Backslash does not means continuation in comments :\
|
| 26 |
+
x = 0
|
| 27 |
+
self.assertEquals(x, 0, 'backslash ending comment')
|
| 28 |
+
|
| 29 |
+
def testPlainIntegers(self):
|
| 30 |
+
self.assertEquals(type(000), type(0))
|
| 31 |
+
self.assertEquals(0xff, 255)
|
| 32 |
+
self.assertEquals(0o377, 255)
|
| 33 |
+
self.assertEquals(2147483647, 0o17777777777)
|
| 34 |
+
self.assertEquals(0b1001, 9)
|
| 35 |
+
# "0x" is not a valid literal
|
| 36 |
+
self.assertRaises(SyntaxError, eval, "0x")
|
| 37 |
+
from sys import maxsize
|
| 38 |
+
if maxsize == 2147483647:
|
| 39 |
+
self.assertEquals(-2147483647-1, -0o20000000000)
|
| 40 |
+
# XXX -2147483648
|
| 41 |
+
self.assert_(0o37777777777 > 0)
|
| 42 |
+
self.assert_(0xffffffff > 0)
|
| 43 |
+
self.assert_(0b1111111111111111111111111111111 > 0)
|
| 44 |
+
for s in ('2147483648', '0o40000000000', '0x100000000',
|
| 45 |
+
'0b10000000000000000000000000000000'):
|
| 46 |
+
try:
|
| 47 |
+
x = eval(s)
|
| 48 |
+
except OverflowError:
|
| 49 |
+
self.fail("OverflowError on huge integer literal %r" % s)
|
| 50 |
+
elif maxsize == 9223372036854775807:
|
| 51 |
+
self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
|
| 52 |
+
self.assert_(0o1777777777777777777777 > 0)
|
| 53 |
+
self.assert_(0xffffffffffffffff > 0)
|
| 54 |
+
self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
|
| 55 |
+
for s in '9223372036854775808', '0o2000000000000000000000', \
|
| 56 |
+
'0x10000000000000000', \
|
| 57 |
+
'0b100000000000000000000000000000000000000000000000000000000000000':
|
| 58 |
+
try:
|
| 59 |
+
x = eval(s)
|
| 60 |
+
except OverflowError:
|
| 61 |
+
self.fail("OverflowError on huge integer literal %r" % s)
|
| 62 |
+
else:
|
| 63 |
+
self.fail('Weird maxsize value %r' % maxsize)
|
| 64 |
+
|
| 65 |
+
def testLongIntegers(self):
|
| 66 |
+
x = 0
|
| 67 |
+
x = 0xffffffffffffffff
|
| 68 |
+
x = 0Xffffffffffffffff
|
| 69 |
+
x = 0o77777777777777777
|
| 70 |
+
x = 0O77777777777777777
|
| 71 |
+
x = 123456789012345678901234567890
|
| 72 |
+
x = 0b100000000000000000000000000000000000000000000000000000000000000000000
|
| 73 |
+
x = 0B111111111111111111111111111111111111111111111111111111111111111111111
|
| 74 |
+
|
| 75 |
+
def testUnderscoresInNumbers(self):
|
| 76 |
+
# Integers
|
| 77 |
+
x = 1_0
|
| 78 |
+
x = 123_456_7_89
|
| 79 |
+
x = 0xabc_123_4_5
|
| 80 |
+
x = 0X_abc_123
|
| 81 |
+
x = 0B11_01
|
| 82 |
+
x = 0b_11_01
|
| 83 |
+
x = 0o45_67
|
| 84 |
+
x = 0O_45_67
|
| 85 |
+
|
| 86 |
+
# Floats
|
| 87 |
+
x = 3_1.4
|
| 88 |
+
x = 03_1.4
|
| 89 |
+
x = 3_1.
|
| 90 |
+
x = .3_1
|
| 91 |
+
x = 3.1_4
|
| 92 |
+
x = 0_3.1_4
|
| 93 |
+
x = 3e1_4
|
| 94 |
+
x = 3_1e+4_1
|
| 95 |
+
x = 3_1E-4_1
|
| 96 |
+
|
| 97 |
+
def testFloats(self):
|
| 98 |
+
x = 3.14
|
| 99 |
+
x = 314.
|
| 100 |
+
x = 0.314
|
| 101 |
+
# XXX x = 000.314
|
| 102 |
+
x = .314
|
| 103 |
+
x = 3e14
|
| 104 |
+
x = 3E14
|
| 105 |
+
x = 3e-14
|
| 106 |
+
x = 3e+14
|
| 107 |
+
x = 3.e14
|
| 108 |
+
x = .3e14
|
| 109 |
+
x = 3.1e4
|
| 110 |
+
|
| 111 |
+
def testStringLiterals(self):
|
| 112 |
+
x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
|
| 113 |
+
x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
|
| 114 |
+
x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
|
| 115 |
+
x = "doesn't \"shrink\" does it"
|
| 116 |
+
y = 'doesn\'t "shrink" does it'
|
| 117 |
+
self.assert_(len(x) == 24 and x == y)
|
| 118 |
+
x = "does \"shrink\" doesn't it"
|
| 119 |
+
y = 'does "shrink" doesn\'t it'
|
| 120 |
+
self.assert_(len(x) == 24 and x == y)
|
| 121 |
+
x = """
|
| 122 |
+
The "quick"
|
| 123 |
+
brown fox
|
| 124 |
+
jumps over
|
| 125 |
+
the 'lazy' dog.
|
| 126 |
+
"""
|
| 127 |
+
y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
|
| 128 |
+
self.assertEquals(x, y)
|
| 129 |
+
y = '''
|
| 130 |
+
The "quick"
|
| 131 |
+
brown fox
|
| 132 |
+
jumps over
|
| 133 |
+
the 'lazy' dog.
|
| 134 |
+
'''
|
| 135 |
+
self.assertEquals(x, y)
|
| 136 |
+
y = "\n\
|
| 137 |
+
The \"quick\"\n\
|
| 138 |
+
brown fox\n\
|
| 139 |
+
jumps over\n\
|
| 140 |
+
the 'lazy' dog.\n\
|
| 141 |
+
"
|
| 142 |
+
self.assertEquals(x, y)
|
| 143 |
+
y = '\n\
|
| 144 |
+
The \"quick\"\n\
|
| 145 |
+
brown fox\n\
|
| 146 |
+
jumps over\n\
|
| 147 |
+
the \'lazy\' dog.\n\
|
| 148 |
+
'
|
| 149 |
+
self.assertEquals(x, y)
|
| 150 |
+
x = rf"hello \{True}"; y = f"hello \\{True}"
|
| 151 |
+
self.assertEquals(x, y)
|
| 152 |
+
|
| 153 |
+
def testEllipsis(self):
|
| 154 |
+
x = ...
|
| 155 |
+
self.assert_(x is Ellipsis)
|
| 156 |
+
self.assertRaises(SyntaxError, eval, ".. .")
|
| 157 |
+
|
| 158 |
+
class GrammarTests(unittest.TestCase):
|
| 159 |
+
|
| 160 |
+
# single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
|
| 161 |
+
# XXX can't test in a script -- this rule is only used when interactive
|
| 162 |
+
|
| 163 |
+
# file_input: (NEWLINE | stmt)* ENDMARKER
|
| 164 |
+
# Being tested as this very moment this very module
|
| 165 |
+
|
| 166 |
+
# expr_input: testlist NEWLINE
|
| 167 |
+
# XXX Hard to test -- used only in calls to input()
|
| 168 |
+
|
| 169 |
+
def testEvalInput(self):
|
| 170 |
+
# testlist ENDMARKER
|
| 171 |
+
x = eval('1, 0 or 1')
|
| 172 |
+
|
| 173 |
+
def testFuncdef(self):
|
| 174 |
+
### [decorators] 'def' NAME parameters ['->' test] ':' suite
|
| 175 |
+
### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
|
| 176 |
+
### decorators: decorator+
|
| 177 |
+
### parameters: '(' [typedargslist] ')'
|
| 178 |
+
### typedargslist: ((tfpdef ['=' test] ',')*
|
| 179 |
+
### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
|
| 180 |
+
### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
|
| 181 |
+
### tfpdef: NAME [':' test]
|
| 182 |
+
### varargslist: ((vfpdef ['=' test] ',')*
|
| 183 |
+
### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
|
| 184 |
+
### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
|
| 185 |
+
### vfpdef: NAME
|
| 186 |
+
def f1(): pass
|
| 187 |
+
f1()
|
| 188 |
+
f1(*())
|
| 189 |
+
f1(*(), **{})
|
| 190 |
+
def f2(one_argument): pass
|
| 191 |
+
def f3(two, arguments): pass
|
| 192 |
+
self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
|
| 193 |
+
self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
|
| 194 |
+
def a1(one_arg,): pass
|
| 195 |
+
def a2(two, args,): pass
|
| 196 |
+
def v0(*rest): pass
|
| 197 |
+
def v1(a, *rest): pass
|
| 198 |
+
def v2(a, b, *rest): pass
|
| 199 |
+
|
| 200 |
+
f1()
|
| 201 |
+
f2(1)
|
| 202 |
+
f2(1,)
|
| 203 |
+
f3(1, 2)
|
| 204 |
+
f3(1, 2,)
|
| 205 |
+
v0()
|
| 206 |
+
v0(1)
|
| 207 |
+
v0(1,)
|
| 208 |
+
v0(1,2)
|
| 209 |
+
v0(1,2,3,4,5,6,7,8,9,0)
|
| 210 |
+
v1(1)
|
| 211 |
+
v1(1,)
|
| 212 |
+
v1(1,2)
|
| 213 |
+
v1(1,2,3)
|
| 214 |
+
v1(1,2,3,4,5,6,7,8,9,0)
|
| 215 |
+
v2(1,2)
|
| 216 |
+
v2(1,2,3)
|
| 217 |
+
v2(1,2,3,4)
|
| 218 |
+
v2(1,2,3,4,5,6,7,8,9,0)
|
| 219 |
+
|
| 220 |
+
def d01(a=1): pass
|
| 221 |
+
d01()
|
| 222 |
+
d01(1)
|
| 223 |
+
d01(*(1,))
|
| 224 |
+
d01(**{'a':2})
|
| 225 |
+
def d11(a, b=1): pass
|
| 226 |
+
d11(1)
|
| 227 |
+
d11(1, 2)
|
| 228 |
+
d11(1, **{'b':2})
|
| 229 |
+
def d21(a, b, c=1): pass
|
| 230 |
+
d21(1, 2)
|
| 231 |
+
d21(1, 2, 3)
|
| 232 |
+
d21(*(1, 2, 3))
|
| 233 |
+
d21(1, *(2, 3))
|
| 234 |
+
d21(1, 2, *(3,))
|
| 235 |
+
d21(1, 2, **{'c':3})
|
| 236 |
+
def d02(a=1, b=2): pass
|
| 237 |
+
d02()
|
| 238 |
+
d02(1)
|
| 239 |
+
d02(1, 2)
|
| 240 |
+
d02(*(1, 2))
|
| 241 |
+
d02(1, *(2,))
|
| 242 |
+
d02(1, **{'b':2})
|
| 243 |
+
d02(**{'a': 1, 'b': 2})
|
| 244 |
+
def d12(a, b=1, c=2): pass
|
| 245 |
+
d12(1)
|
| 246 |
+
d12(1, 2)
|
| 247 |
+
d12(1, 2, 3)
|
| 248 |
+
def d22(a, b, c=1, d=2): pass
|
| 249 |
+
d22(1, 2)
|
| 250 |
+
d22(1, 2, 3)
|
| 251 |
+
d22(1, 2, 3, 4)
|
| 252 |
+
def d01v(a=1, *rest): pass
|
| 253 |
+
d01v()
|
| 254 |
+
d01v(1)
|
| 255 |
+
d01v(1, 2)
|
| 256 |
+
d01v(*(1, 2, 3, 4))
|
| 257 |
+
d01v(*(1,))
|
| 258 |
+
d01v(**{'a':2})
|
| 259 |
+
def d11v(a, b=1, *rest): pass
|
| 260 |
+
d11v(1)
|
| 261 |
+
d11v(1, 2)
|
| 262 |
+
d11v(1, 2, 3)
|
| 263 |
+
def d21v(a, b, c=1, *rest): pass
|
| 264 |
+
d21v(1, 2)
|
| 265 |
+
d21v(1, 2, 3)
|
| 266 |
+
d21v(1, 2, 3, 4)
|
| 267 |
+
d21v(*(1, 2, 3, 4))
|
| 268 |
+
d21v(1, 2, **{'c': 3})
|
| 269 |
+
def d02v(a=1, b=2, *rest): pass
|
| 270 |
+
d02v()
|
| 271 |
+
d02v(1)
|
| 272 |
+
d02v(1, 2)
|
| 273 |
+
d02v(1, 2, 3)
|
| 274 |
+
d02v(1, *(2, 3, 4))
|
| 275 |
+
d02v(**{'a': 1, 'b': 2})
|
| 276 |
+
def d12v(a, b=1, c=2, *rest): pass
|
| 277 |
+
d12v(1)
|
| 278 |
+
d12v(1, 2)
|
| 279 |
+
d12v(1, 2, 3)
|
| 280 |
+
d12v(1, 2, 3, 4)
|
| 281 |
+
d12v(*(1, 2, 3, 4))
|
| 282 |
+
d12v(1, 2, *(3, 4, 5))
|
| 283 |
+
d12v(1, *(2,), **{'c': 3})
|
| 284 |
+
def d22v(a, b, c=1, d=2, *rest): pass
|
| 285 |
+
d22v(1, 2)
|
| 286 |
+
d22v(1, 2, 3)
|
| 287 |
+
d22v(1, 2, 3, 4)
|
| 288 |
+
d22v(1, 2, 3, 4, 5)
|
| 289 |
+
d22v(*(1, 2, 3, 4))
|
| 290 |
+
d22v(1, 2, *(3, 4, 5))
|
| 291 |
+
d22v(1, *(2, 3), **{'d': 4})
|
| 292 |
+
|
| 293 |
+
# keyword argument type tests
|
| 294 |
+
try:
|
| 295 |
+
str('x', **{b'foo':1 })
|
| 296 |
+
except TypeError:
|
| 297 |
+
pass
|
| 298 |
+
else:
|
| 299 |
+
self.fail('Bytes should not work as keyword argument names')
|
| 300 |
+
# keyword only argument tests
|
| 301 |
+
def pos0key1(*, key): return key
|
| 302 |
+
pos0key1(key=100)
|
| 303 |
+
def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
|
| 304 |
+
pos2key2(1, 2, k1=100)
|
| 305 |
+
pos2key2(1, 2, k1=100, k2=200)
|
| 306 |
+
pos2key2(1, 2, k2=100, k1=200)
|
| 307 |
+
def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
|
| 308 |
+
pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
|
| 309 |
+
pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
|
| 310 |
+
|
| 311 |
+
# keyword arguments after *arglist
|
| 312 |
+
def f(*args, **kwargs):
|
| 313 |
+
return args, kwargs
|
| 314 |
+
self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
|
| 315 |
+
{'x':2, 'y':5}))
|
| 316 |
+
self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
|
| 317 |
+
self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
|
| 318 |
+
|
| 319 |
+
# argument annotation tests
|
| 320 |
+
def f(x) -> list: pass
|
| 321 |
+
self.assertEquals(f.__annotations__, {'return': list})
|
| 322 |
+
def f(x:int): pass
|
| 323 |
+
self.assertEquals(f.__annotations__, {'x': int})
|
| 324 |
+
def f(*x:str): pass
|
| 325 |
+
self.assertEquals(f.__annotations__, {'x': str})
|
| 326 |
+
def f(**x:float): pass
|
| 327 |
+
self.assertEquals(f.__annotations__, {'x': float})
|
| 328 |
+
def f(x, y:1+2): pass
|
| 329 |
+
self.assertEquals(f.__annotations__, {'y': 3})
|
| 330 |
+
def f(a, b:1, c:2, d): pass
|
| 331 |
+
self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
|
| 332 |
+
def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
|
| 333 |
+
self.assertEquals(f.__annotations__,
|
| 334 |
+
{'b': 1, 'c': 2, 'e': 3, 'g': 6})
|
| 335 |
+
def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
|
| 336 |
+
**k:11) -> 12: pass
|
| 337 |
+
self.assertEquals(f.__annotations__,
|
| 338 |
+
{'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
|
| 339 |
+
'k': 11, 'return': 12})
|
| 340 |
+
# Check for SF Bug #1697248 - mixing decorators and a return annotation
|
| 341 |
+
def null(x): return x
|
| 342 |
+
@null
|
| 343 |
+
def f(x) -> list: pass
|
| 344 |
+
self.assertEquals(f.__annotations__, {'return': list})
|
| 345 |
+
|
| 346 |
+
# test closures with a variety of oparg's
|
| 347 |
+
closure = 1
|
| 348 |
+
def f(): return closure
|
| 349 |
+
def f(x=1): return closure
|
| 350 |
+
def f(*, k=1): return closure
|
| 351 |
+
def f() -> int: return closure
|
| 352 |
+
|
| 353 |
+
# Check ast errors in *args and *kwargs
|
| 354 |
+
check_syntax_error(self, "f(*g(1=2))")
|
| 355 |
+
check_syntax_error(self, "f(**g(1=2))")
|
| 356 |
+
|
| 357 |
+
def testLambdef(self):
|
| 358 |
+
### lambdef: 'lambda' [varargslist] ':' test
|
| 359 |
+
l1 = lambda : 0
|
| 360 |
+
self.assertEquals(l1(), 0)
|
| 361 |
+
l2 = lambda : a[d] # XXX just testing the expression
|
| 362 |
+
l3 = lambda : [2 < x for x in [-1, 3, 0]]
|
| 363 |
+
self.assertEquals(l3(), [0, 1, 0])
|
| 364 |
+
l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
|
| 365 |
+
self.assertEquals(l4(), 1)
|
| 366 |
+
l5 = lambda x, y, z=2: x + y + z
|
| 367 |
+
self.assertEquals(l5(1, 2), 5)
|
| 368 |
+
self.assertEquals(l5(1, 2, 3), 6)
|
| 369 |
+
check_syntax_error(self, "lambda x: x = 2")
|
| 370 |
+
check_syntax_error(self, "lambda (None,): None")
|
| 371 |
+
l6 = lambda x, y, *, k=20: x+y+k
|
| 372 |
+
self.assertEquals(l6(1,2), 1+2+20)
|
| 373 |
+
self.assertEquals(l6(1,2,k=10), 1+2+10)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
### stmt: simple_stmt | compound_stmt
|
| 377 |
+
# Tested below
|
| 378 |
+
|
| 379 |
+
def testSimpleStmt(self):
|
| 380 |
+
### simple_stmt: small_stmt (';' small_stmt)* [';']
|
| 381 |
+
x = 1; pass; del x
|
| 382 |
+
def foo():
|
| 383 |
+
# verify statements that end with semi-colons
|
| 384 |
+
x = 1; pass; del x;
|
| 385 |
+
foo()
|
| 386 |
+
|
| 387 |
+
### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
|
| 388 |
+
# Tested below
|
| 389 |
+
|
| 390 |
+
def testExprStmt(self):
|
| 391 |
+
# (exprlist '=')* exprlist
|
| 392 |
+
1
|
| 393 |
+
1, 2, 3
|
| 394 |
+
x = 1
|
| 395 |
+
x = 1, 2, 3
|
| 396 |
+
x = y = z = 1, 2, 3
|
| 397 |
+
x, y, z = 1, 2, 3
|
| 398 |
+
abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
|
| 399 |
+
|
| 400 |
+
check_syntax_error(self, "x + 1 = 1")
|
| 401 |
+
check_syntax_error(self, "a + 1 = b + 2")
|
| 402 |
+
|
| 403 |
+
def testDelStmt(self):
|
| 404 |
+
# 'del' exprlist
|
| 405 |
+
abc = [1,2,3]
|
| 406 |
+
x, y, z = abc
|
| 407 |
+
xyz = x, y, z
|
| 408 |
+
|
| 409 |
+
del abc
|
| 410 |
+
del x, y, (z, xyz)
|
| 411 |
+
|
| 412 |
+
def testPassStmt(self):
|
| 413 |
+
# 'pass'
|
| 414 |
+
pass
|
| 415 |
+
|
| 416 |
+
# flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
|
| 417 |
+
# Tested below
|
| 418 |
+
|
| 419 |
+
def testBreakStmt(self):
|
| 420 |
+
# 'break'
|
| 421 |
+
while 1: break
|
| 422 |
+
|
| 423 |
+
def testContinueStmt(self):
|
| 424 |
+
# 'continue'
|
| 425 |
+
i = 1
|
| 426 |
+
while i: i = 0; continue
|
| 427 |
+
|
| 428 |
+
msg = ""
|
| 429 |
+
while not msg:
|
| 430 |
+
msg = "ok"
|
| 431 |
+
try:
|
| 432 |
+
continue
|
| 433 |
+
msg = "continue failed to continue inside try"
|
| 434 |
+
except:
|
| 435 |
+
msg = "continue inside try called except block"
|
| 436 |
+
if msg != "ok":
|
| 437 |
+
self.fail(msg)
|
| 438 |
+
|
| 439 |
+
msg = ""
|
| 440 |
+
while not msg:
|
| 441 |
+
msg = "finally block not called"
|
| 442 |
+
try:
|
| 443 |
+
continue
|
| 444 |
+
finally:
|
| 445 |
+
msg = "ok"
|
| 446 |
+
if msg != "ok":
|
| 447 |
+
self.fail(msg)
|
| 448 |
+
|
| 449 |
+
def test_break_continue_loop(self):
|
| 450 |
+
# This test warrants an explanation. It is a test specifically for SF bugs
|
| 451 |
+
# #463359 and #462937. The bug is that a 'break' statement executed or
|
| 452 |
+
# exception raised inside a try/except inside a loop, *after* a continue
|
| 453 |
+
# statement has been executed in that loop, will cause the wrong number of
|
| 454 |
+
# arguments to be popped off the stack and the instruction pointer reset to
|
| 455 |
+
# a very small number (usually 0.) Because of this, the following test
|
| 456 |
+
# *must* written as a function, and the tracking vars *must* be function
|
| 457 |
+
# arguments with default values. Otherwise, the test will loop and loop.
|
| 458 |
+
|
| 459 |
+
def test_inner(extra_burning_oil = 1, count=0):
|
| 460 |
+
big_hippo = 2
|
| 461 |
+
while big_hippo:
|
| 462 |
+
count += 1
|
| 463 |
+
try:
|
| 464 |
+
if extra_burning_oil and big_hippo == 1:
|
| 465 |
+
extra_burning_oil -= 1
|
| 466 |
+
break
|
| 467 |
+
big_hippo -= 1
|
| 468 |
+
continue
|
| 469 |
+
except:
|
| 470 |
+
raise
|
| 471 |
+
if count > 2 or big_hippo != 1:
|
| 472 |
+
self.fail("continue then break in try/except in loop broken!")
|
| 473 |
+
test_inner()
|
| 474 |
+
|
| 475 |
+
def testReturn(self):
|
| 476 |
+
# 'return' [testlist_star_expr]
|
| 477 |
+
def g1(): return
|
| 478 |
+
def g2(): return 1
|
| 479 |
+
return_list = [2, 3]
|
| 480 |
+
def g3(): return 1, *return_list
|
| 481 |
+
g1()
|
| 482 |
+
x = g2()
|
| 483 |
+
x3 = g3()
|
| 484 |
+
check_syntax_error(self, "class foo:return 1")
|
| 485 |
+
|
| 486 |
+
def testYield(self):
|
| 487 |
+
# 'yield' [yield_arg]
|
| 488 |
+
def g1(): yield 1
|
| 489 |
+
yield_list = [2, 3]
|
| 490 |
+
def g2(): yield 1, *yield_list
|
| 491 |
+
def g3(): yield from iter(yield_list)
|
| 492 |
+
x1 = g1()
|
| 493 |
+
x2 = g2()
|
| 494 |
+
x3 = g3()
|
| 495 |
+
check_syntax_error(self, "class foo:yield 1")
|
| 496 |
+
check_syntax_error(self, "def g4(): yield from *a")
|
| 497 |
+
|
| 498 |
+
def testRaise(self):
|
| 499 |
+
# 'raise' test [',' test]
|
| 500 |
+
try: raise RuntimeError('just testing')
|
| 501 |
+
except RuntimeError: pass
|
| 502 |
+
try: raise KeyboardInterrupt
|
| 503 |
+
except KeyboardInterrupt: pass
|
| 504 |
+
|
| 505 |
+
def testImport(self):
|
| 506 |
+
# 'import' dotted_as_names
|
| 507 |
+
import sys
|
| 508 |
+
import time, sys
|
| 509 |
+
# 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
|
| 510 |
+
from time import time
|
| 511 |
+
from time import (time)
|
| 512 |
+
# not testable inside a function, but already done at top of the module
|
| 513 |
+
# from sys import *
|
| 514 |
+
from sys import path, argv
|
| 515 |
+
from sys import (path, argv)
|
| 516 |
+
from sys import (path, argv,)
|
| 517 |
+
|
| 518 |
+
def testGlobal(self):
|
| 519 |
+
# 'global' NAME (',' NAME)*
|
| 520 |
+
global a
|
| 521 |
+
global a, b
|
| 522 |
+
global one, two, three, four, five, six, seven, eight, nine, ten
|
| 523 |
+
|
| 524 |
+
def testNonlocal(self):
|
| 525 |
+
# 'nonlocal' NAME (',' NAME)*
|
| 526 |
+
x = 0
|
| 527 |
+
y = 0
|
| 528 |
+
def f():
|
| 529 |
+
nonlocal x
|
| 530 |
+
nonlocal x, y
|
| 531 |
+
|
| 532 |
+
def testAssert(self):
|
| 533 |
+
# assert_stmt: 'assert' test [',' test]
|
| 534 |
+
assert 1
|
| 535 |
+
assert 1, 1
|
| 536 |
+
assert lambda x:x
|
| 537 |
+
assert 1, lambda x:x+1
|
| 538 |
+
try:
|
| 539 |
+
assert 0, "msg"
|
| 540 |
+
except AssertionError as e:
|
| 541 |
+
self.assertEquals(e.args[0], "msg")
|
| 542 |
+
else:
|
| 543 |
+
if __debug__:
|
| 544 |
+
self.fail("AssertionError not raised by assert 0")
|
| 545 |
+
|
| 546 |
+
### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
|
| 547 |
+
# Tested below
|
| 548 |
+
|
| 549 |
+
def testIf(self):
|
| 550 |
+
# 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
|
| 551 |
+
if 1: pass
|
| 552 |
+
if 1: pass
|
| 553 |
+
else: pass
|
| 554 |
+
if 0: pass
|
| 555 |
+
elif 0: pass
|
| 556 |
+
if 0: pass
|
| 557 |
+
elif 0: pass
|
| 558 |
+
elif 0: pass
|
| 559 |
+
elif 0: pass
|
| 560 |
+
else: pass
|
| 561 |
+
|
| 562 |
+
def testWhile(self):
|
| 563 |
+
# 'while' test ':' suite ['else' ':' suite]
|
| 564 |
+
while 0: pass
|
| 565 |
+
while 0: pass
|
| 566 |
+
else: pass
|
| 567 |
+
|
| 568 |
+
# Issue1920: "while 0" is optimized away,
|
| 569 |
+
# ensure that the "else" clause is still present.
|
| 570 |
+
x = 0
|
| 571 |
+
while 0:
|
| 572 |
+
x = 1
|
| 573 |
+
else:
|
| 574 |
+
x = 2
|
| 575 |
+
self.assertEquals(x, 2)
|
| 576 |
+
|
| 577 |
+
def testFor(self):
|
| 578 |
+
# 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
|
| 579 |
+
for i in 1, 2, 3: pass
|
| 580 |
+
for i, j, k in (): pass
|
| 581 |
+
else: pass
|
| 582 |
+
class Squares:
|
| 583 |
+
def __init__(self, max):
|
| 584 |
+
self.max = max
|
| 585 |
+
self.sofar = []
|
| 586 |
+
def __len__(self): return len(self.sofar)
|
| 587 |
+
def __getitem__(self, i):
|
| 588 |
+
if not 0 <= i < self.max: raise IndexError
|
| 589 |
+
n = len(self.sofar)
|
| 590 |
+
while n <= i:
|
| 591 |
+
self.sofar.append(n*n)
|
| 592 |
+
n = n+1
|
| 593 |
+
return self.sofar[i]
|
| 594 |
+
n = 0
|
| 595 |
+
for x in Squares(10): n = n+x
|
| 596 |
+
if n != 285:
|
| 597 |
+
self.fail('for over growing sequence')
|
| 598 |
+
|
| 599 |
+
result = []
|
| 600 |
+
for x, in [(1,), (2,), (3,)]:
|
| 601 |
+
result.append(x)
|
| 602 |
+
self.assertEqual(result, [1, 2, 3])
|
| 603 |
+
|
| 604 |
+
def testTry(self):
|
| 605 |
+
### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
|
| 606 |
+
### | 'try' ':' suite 'finally' ':' suite
|
| 607 |
+
### except_clause: 'except' [expr ['as' expr]]
|
| 608 |
+
try:
|
| 609 |
+
1/0
|
| 610 |
+
except ZeroDivisionError:
|
| 611 |
+
pass
|
| 612 |
+
else:
|
| 613 |
+
pass
|
| 614 |
+
try: 1/0
|
| 615 |
+
except EOFError: pass
|
| 616 |
+
except TypeError as msg: pass
|
| 617 |
+
except RuntimeError as msg: pass
|
| 618 |
+
except: pass
|
| 619 |
+
else: pass
|
| 620 |
+
try: 1/0
|
| 621 |
+
except (EOFError, TypeError, ZeroDivisionError): pass
|
| 622 |
+
try: 1/0
|
| 623 |
+
except (EOFError, TypeError, ZeroDivisionError) as msg: pass
|
| 624 |
+
try: pass
|
| 625 |
+
finally: pass
|
| 626 |
+
|
| 627 |
+
def testSuite(self):
|
| 628 |
+
# simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
|
| 629 |
+
if 1: pass
|
| 630 |
+
if 1:
|
| 631 |
+
pass
|
| 632 |
+
if 1:
|
| 633 |
+
#
|
| 634 |
+
#
|
| 635 |
+
#
|
| 636 |
+
pass
|
| 637 |
+
pass
|
| 638 |
+
#
|
| 639 |
+
pass
|
| 640 |
+
#
|
| 641 |
+
|
| 642 |
+
def testTest(self):
|
| 643 |
+
### and_test ('or' and_test)*
|
| 644 |
+
### and_test: not_test ('and' not_test)*
|
| 645 |
+
### not_test: 'not' not_test | comparison
|
| 646 |
+
if not 1: pass
|
| 647 |
+
if 1 and 1: pass
|
| 648 |
+
if 1 or 1: pass
|
| 649 |
+
if not not not 1: pass
|
| 650 |
+
if not 1 and 1 and 1: pass
|
| 651 |
+
if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
|
| 652 |
+
|
| 653 |
+
def testComparison(self):
|
| 654 |
+
### comparison: expr (comp_op expr)*
|
| 655 |
+
### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
|
| 656 |
+
if 1: pass
|
| 657 |
+
x = (1 == 1)
|
| 658 |
+
if 1 == 1: pass
|
| 659 |
+
if 1 != 1: pass
|
| 660 |
+
if 1 < 1: pass
|
| 661 |
+
if 1 > 1: pass
|
| 662 |
+
if 1 <= 1: pass
|
| 663 |
+
if 1 >= 1: pass
|
| 664 |
+
if 1 is 1: pass
|
| 665 |
+
if 1 is not 1: pass
|
| 666 |
+
if 1 in (): pass
|
| 667 |
+
if 1 not in (): pass
|
| 668 |
+
if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
|
| 669 |
+
|
| 670 |
+
def testBinaryMaskOps(self):
|
| 671 |
+
x = 1 & 1
|
| 672 |
+
x = 1 ^ 1
|
| 673 |
+
x = 1 | 1
|
| 674 |
+
|
| 675 |
+
def testShiftOps(self):
|
| 676 |
+
x = 1 << 1
|
| 677 |
+
x = 1 >> 1
|
| 678 |
+
x = 1 << 1 >> 1
|
| 679 |
+
|
| 680 |
+
def testAdditiveOps(self):
|
| 681 |
+
x = 1
|
| 682 |
+
x = 1 + 1
|
| 683 |
+
x = 1 - 1 - 1
|
| 684 |
+
x = 1 - 1 + 1 - 1 + 1
|
| 685 |
+
|
| 686 |
+
def testMultiplicativeOps(self):
|
| 687 |
+
x = 1 * 1
|
| 688 |
+
x = 1 / 1
|
| 689 |
+
x = 1 % 1
|
| 690 |
+
x = 1 / 1 * 1 % 1
|
| 691 |
+
|
| 692 |
+
def testUnaryOps(self):
|
| 693 |
+
x = +1
|
| 694 |
+
x = -1
|
| 695 |
+
x = ~1
|
| 696 |
+
x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
|
| 697 |
+
x = -1*1/1 + 1*1 - ---1*1
|
| 698 |
+
|
| 699 |
+
def testSelectors(self):
|
| 700 |
+
### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
|
| 701 |
+
### subscript: expr | [expr] ':' [expr]
|
| 702 |
+
|
| 703 |
+
import sys, time
|
| 704 |
+
c = sys.path[0]
|
| 705 |
+
x = time.time()
|
| 706 |
+
x = sys.modules['time'].time()
|
| 707 |
+
a = '01234'
|
| 708 |
+
c = a[0]
|
| 709 |
+
c = a[-1]
|
| 710 |
+
s = a[0:5]
|
| 711 |
+
s = a[:5]
|
| 712 |
+
s = a[0:]
|
| 713 |
+
s = a[:]
|
| 714 |
+
s = a[-5:]
|
| 715 |
+
s = a[:-1]
|
| 716 |
+
s = a[-4:-3]
|
| 717 |
+
# A rough test of SF bug 1333982. https://python.org/sf/1333982
|
| 718 |
+
# The testing here is fairly incomplete.
|
| 719 |
+
# Test cases should include: commas with 1 and 2 colons
|
| 720 |
+
d = {}
|
| 721 |
+
d[1] = 1
|
| 722 |
+
d[1,] = 2
|
| 723 |
+
d[1,2] = 3
|
| 724 |
+
d[1,2,3] = 4
|
| 725 |
+
L = list(d)
|
| 726 |
+
L.sort(key=lambda x: x if isinstance(x, tuple) else ())
|
| 727 |
+
self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
|
| 728 |
+
|
| 729 |
+
def testAtoms(self):
|
| 730 |
+
### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
|
| 731 |
+
### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
|
| 732 |
+
|
| 733 |
+
x = (1)
|
| 734 |
+
x = (1 or 2 or 3)
|
| 735 |
+
x = (1 or 2 or 3, 2, 3)
|
| 736 |
+
|
| 737 |
+
x = []
|
| 738 |
+
x = [1]
|
| 739 |
+
x = [1 or 2 or 3]
|
| 740 |
+
x = [1 or 2 or 3, 2, 3]
|
| 741 |
+
x = []
|
| 742 |
+
|
| 743 |
+
x = {}
|
| 744 |
+
x = {'one': 1}
|
| 745 |
+
x = {'one': 1,}
|
| 746 |
+
x = {'one' or 'two': 1 or 2}
|
| 747 |
+
x = {'one': 1, 'two': 2}
|
| 748 |
+
x = {'one': 1, 'two': 2,}
|
| 749 |
+
x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
|
| 750 |
+
|
| 751 |
+
x = {'one'}
|
| 752 |
+
x = {'one', 1,}
|
| 753 |
+
x = {'one', 'two', 'three'}
|
| 754 |
+
x = {2, 3, 4,}
|
| 755 |
+
|
| 756 |
+
x = x
|
| 757 |
+
x = 'x'
|
| 758 |
+
x = 123
|
| 759 |
+
|
| 760 |
+
### exprlist: expr (',' expr)* [',']
|
| 761 |
+
### testlist: test (',' test)* [',']
|
| 762 |
+
# These have been exercised enough above
|
| 763 |
+
|
| 764 |
+
def testClassdef(self):
|
| 765 |
+
# 'class' NAME ['(' [testlist] ')'] ':' suite
|
| 766 |
+
class B: pass
|
| 767 |
+
class B2(): pass
|
| 768 |
+
class C1(B): pass
|
| 769 |
+
class C2(B): pass
|
| 770 |
+
class D(C1, C2, B): pass
|
| 771 |
+
class C:
|
| 772 |
+
def meth1(self): pass
|
| 773 |
+
def meth2(self, arg): pass
|
| 774 |
+
def meth3(self, a1, a2): pass
|
| 775 |
+
|
| 776 |
+
# decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
|
| 777 |
+
# decorators: decorator+
|
| 778 |
+
# decorated: decorators (classdef | funcdef)
|
| 779 |
+
def class_decorator(x): return x
|
| 780 |
+
@class_decorator
|
| 781 |
+
class G: pass
|
| 782 |
+
|
| 783 |
+
def testDictcomps(self):
|
| 784 |
+
# dictorsetmaker: ( (test ':' test (comp_for |
|
| 785 |
+
# (',' test ':' test)* [','])) |
|
| 786 |
+
# (test (comp_for | (',' test)* [','])) )
|
| 787 |
+
nums = [1, 2, 3]
|
| 788 |
+
self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
|
| 789 |
+
|
| 790 |
+
def testListcomps(self):
|
| 791 |
+
# list comprehension tests
|
| 792 |
+
nums = [1, 2, 3, 4, 5]
|
| 793 |
+
strs = ["Apple", "Banana", "Coconut"]
|
| 794 |
+
spcs = [" Apple", " Banana ", "Coco nut "]
|
| 795 |
+
|
| 796 |
+
self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
|
| 797 |
+
self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
|
| 798 |
+
self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
|
| 799 |
+
self.assertEqual([(i, s) for i in nums for s in strs],
|
| 800 |
+
[(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
|
| 801 |
+
(2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
|
| 802 |
+
(3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
|
| 803 |
+
(4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
|
| 804 |
+
(5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
|
| 805 |
+
self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
|
| 806 |
+
[(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
|
| 807 |
+
(3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
|
| 808 |
+
(5, 'Banana'), (5, 'Coconut')])
|
| 809 |
+
self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
|
| 810 |
+
[[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
|
| 811 |
+
|
| 812 |
+
def test_in_func(l):
|
| 813 |
+
return [0 < x < 3 for x in l if x > 2]
|
| 814 |
+
|
| 815 |
+
self.assertEqual(test_in_func(nums), [False, False, False])
|
| 816 |
+
|
| 817 |
+
def test_nested_front():
|
| 818 |
+
self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
|
| 819 |
+
[[1, 2], [3, 4], [5, 6]])
|
| 820 |
+
|
| 821 |
+
test_nested_front()
|
| 822 |
+
|
| 823 |
+
check_syntax_error(self, "[i, s for i in nums for s in strs]")
|
| 824 |
+
check_syntax_error(self, "[x if y]")
|
| 825 |
+
|
| 826 |
+
suppliers = [
|
| 827 |
+
(1, "Boeing"),
|
| 828 |
+
(2, "Ford"),
|
| 829 |
+
(3, "Macdonalds")
|
| 830 |
+
]
|
| 831 |
+
|
| 832 |
+
parts = [
|
| 833 |
+
(10, "Airliner"),
|
| 834 |
+
(20, "Engine"),
|
| 835 |
+
(30, "Cheeseburger")
|
| 836 |
+
]
|
| 837 |
+
|
| 838 |
+
suppart = [
|
| 839 |
+
(1, 10), (1, 20), (2, 20), (3, 30)
|
| 840 |
+
]
|
| 841 |
+
|
| 842 |
+
x = [
|
| 843 |
+
(sname, pname)
|
| 844 |
+
for (sno, sname) in suppliers
|
| 845 |
+
for (pno, pname) in parts
|
| 846 |
+
for (sp_sno, sp_pno) in suppart
|
| 847 |
+
if sno == sp_sno and pno == sp_pno
|
| 848 |
+
]
|
| 849 |
+
|
| 850 |
+
self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
|
| 851 |
+
('Macdonalds', 'Cheeseburger')])
|
| 852 |
+
|
| 853 |
+
def testGenexps(self):
|
| 854 |
+
# generator expression tests
|
| 855 |
+
g = ([x for x in range(10)] for x in range(1))
|
| 856 |
+
self.assertEqual(next(g), [x for x in range(10)])
|
| 857 |
+
try:
|
| 858 |
+
next(g)
|
| 859 |
+
self.fail('should produce StopIteration exception')
|
| 860 |
+
except StopIteration:
|
| 861 |
+
pass
|
| 862 |
+
|
| 863 |
+
a = 1
|
| 864 |
+
try:
|
| 865 |
+
g = (a for d in a)
|
| 866 |
+
next(g)
|
| 867 |
+
self.fail('should produce TypeError')
|
| 868 |
+
except TypeError:
|
| 869 |
+
pass
|
| 870 |
+
|
| 871 |
+
self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
|
| 872 |
+
self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
|
| 873 |
+
|
| 874 |
+
a = [x for x in range(10)]
|
| 875 |
+
b = (x for x in (y for y in a))
|
| 876 |
+
self.assertEqual(sum(b), sum([x for x in range(10)]))
|
| 877 |
+
|
| 878 |
+
self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
|
| 879 |
+
self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
|
| 880 |
+
self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
|
| 881 |
+
self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
|
| 882 |
+
self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
|
| 883 |
+
self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
|
| 884 |
+
self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
|
| 885 |
+
check_syntax_error(self, "foo(x for x in range(10), 100)")
|
| 886 |
+
check_syntax_error(self, "foo(100, x for x in range(10))")
|
| 887 |
+
|
| 888 |
+
def testComprehensionSpecials(self):
|
| 889 |
+
# test for outmost iterable precomputation
|
| 890 |
+
x = 10; g = (i for i in range(x)); x = 5
|
| 891 |
+
self.assertEqual(len(list(g)), 10)
|
| 892 |
+
|
| 893 |
+
# This should hold, since we're only precomputing outmost iterable.
|
| 894 |
+
x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
|
| 895 |
+
x = 5; t = True;
|
| 896 |
+
self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
|
| 897 |
+
|
| 898 |
+
# Grammar allows multiple adjacent 'if's in listcomps and genexps,
|
| 899 |
+
# even though it's silly. Make sure it works (ifelse broke this.)
|
| 900 |
+
self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
|
| 901 |
+
self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
|
| 902 |
+
|
| 903 |
+
# verify unpacking single element tuples in listcomp/genexp.
|
| 904 |
+
self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
|
| 905 |
+
self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
|
| 906 |
+
|
| 907 |
+
def test_with_statement(self):
|
| 908 |
+
class manager(object):
|
| 909 |
+
def __enter__(self):
|
| 910 |
+
return (1, 2)
|
| 911 |
+
def __exit__(self, *args):
|
| 912 |
+
pass
|
| 913 |
+
|
| 914 |
+
with manager():
|
| 915 |
+
pass
|
| 916 |
+
with manager() as x:
|
| 917 |
+
pass
|
| 918 |
+
with manager() as (x, y):
|
| 919 |
+
pass
|
| 920 |
+
with manager(), manager():
|
| 921 |
+
pass
|
| 922 |
+
with manager() as x, manager() as y:
|
| 923 |
+
pass
|
| 924 |
+
with manager() as x, manager():
|
| 925 |
+
pass
|
| 926 |
+
|
| 927 |
+
def testIfElseExpr(self):
|
| 928 |
+
# Test ifelse expressions in various cases
|
| 929 |
+
def _checkeval(msg, ret):
|
| 930 |
+
"helper to check that evaluation of expressions is done correctly"
|
| 931 |
+
print(x)
|
| 932 |
+
return ret
|
| 933 |
+
|
| 934 |
+
# the next line is not allowed anymore
|
| 935 |
+
#self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
|
| 936 |
+
self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
|
| 937 |
+
self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
|
| 938 |
+
self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
|
| 939 |
+
self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
|
| 940 |
+
self.assertEqual((5 and 6 if 0 else 1), 1)
|
| 941 |
+
self.assertEqual(((5 and 6) if 0 else 1), 1)
|
| 942 |
+
self.assertEqual((5 and (6 if 1 else 1)), 6)
|
| 943 |
+
self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
|
| 944 |
+
self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
|
| 945 |
+
self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
|
| 946 |
+
self.assertEqual((not 5 if 1 else 1), False)
|
| 947 |
+
self.assertEqual((not 5 if 0 else 1), 1)
|
| 948 |
+
self.assertEqual((6 + 1 if 1 else 2), 7)
|
| 949 |
+
self.assertEqual((6 - 1 if 1 else 2), 5)
|
| 950 |
+
self.assertEqual((6 * 2 if 1 else 4), 12)
|
| 951 |
+
self.assertEqual((6 / 2 if 1 else 3), 3)
|
| 952 |
+
self.assertEqual((6 < 4 if 0 else 2), 2)
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
if __name__ == '__main__':
|
| 956 |
+
unittest.main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/pytree_idempotency.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright 2006 Google, Inc. All Rights Reserved.
|
| 3 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 4 |
+
|
| 5 |
+
"""Main program for testing the infrastructure."""
|
| 6 |
+
|
| 7 |
+
from __future__ import print_function
|
| 8 |
+
|
| 9 |
+
__author__ = "Guido van Rossum <guido@python.org>"
|
| 10 |
+
|
| 11 |
+
# Support imports (need to be imported first)
|
| 12 |
+
from . import support
|
| 13 |
+
|
| 14 |
+
# Python imports
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
+
# Local imports
|
| 20 |
+
from .. import pytree
|
| 21 |
+
from .. import pgen2
|
| 22 |
+
from ..pgen2 import driver
|
| 23 |
+
|
| 24 |
+
logging.basicConfig()
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
gr = driver.load_grammar("Grammar.txt")
|
| 28 |
+
dr = driver.Driver(gr, convert=pytree.convert)
|
| 29 |
+
|
| 30 |
+
fn = "example.py"
|
| 31 |
+
tree = dr.parse_file(fn, debug=True)
|
| 32 |
+
if not diff(fn, tree):
|
| 33 |
+
print("No diffs.")
|
| 34 |
+
if not sys.argv[1:]:
|
| 35 |
+
return # Pass a dummy argument to run the complete test suite below
|
| 36 |
+
|
| 37 |
+
problems = []
|
| 38 |
+
|
| 39 |
+
# Process every imported module
|
| 40 |
+
for name in sys.modules:
|
| 41 |
+
mod = sys.modules[name]
|
| 42 |
+
if mod is None or not hasattr(mod, "__file__"):
|
| 43 |
+
continue
|
| 44 |
+
fn = mod.__file__
|
| 45 |
+
if fn.endswith(".pyc"):
|
| 46 |
+
fn = fn[:-1]
|
| 47 |
+
if not fn.endswith(".py"):
|
| 48 |
+
continue
|
| 49 |
+
print("Parsing", fn, file=sys.stderr)
|
| 50 |
+
tree = dr.parse_file(fn, debug=True)
|
| 51 |
+
if diff(fn, tree):
|
| 52 |
+
problems.append(fn)
|
| 53 |
+
|
| 54 |
+
# Process every single module on sys.path (but not in packages)
|
| 55 |
+
for dir in sys.path:
|
| 56 |
+
try:
|
| 57 |
+
names = os.listdir(dir)
|
| 58 |
+
except OSError:
|
| 59 |
+
continue
|
| 60 |
+
print("Scanning", dir, "...", file=sys.stderr)
|
| 61 |
+
for name in names:
|
| 62 |
+
if not name.endswith(".py"):
|
| 63 |
+
continue
|
| 64 |
+
print("Parsing", name, file=sys.stderr)
|
| 65 |
+
fn = os.path.join(dir, name)
|
| 66 |
+
try:
|
| 67 |
+
tree = dr.parse_file(fn, debug=True)
|
| 68 |
+
except pgen2.parse.ParseError as err:
|
| 69 |
+
print("ParseError:", err)
|
| 70 |
+
else:
|
| 71 |
+
if diff(fn, tree):
|
| 72 |
+
problems.append(fn)
|
| 73 |
+
|
| 74 |
+
# Show summary of problem files
|
| 75 |
+
if not problems:
|
| 76 |
+
print("No problems. Congratulations!")
|
| 77 |
+
else:
|
| 78 |
+
print("Problems in following files:")
|
| 79 |
+
for fn in problems:
|
| 80 |
+
print("***", fn)
|
| 81 |
+
|
| 82 |
+
def diff(fn, tree):
|
| 83 |
+
f = open("@", "w")
|
| 84 |
+
try:
|
| 85 |
+
f.write(str(tree))
|
| 86 |
+
finally:
|
| 87 |
+
f.close()
|
| 88 |
+
try:
|
| 89 |
+
return os.system("diff -u %s @" % fn)
|
| 90 |
+
finally:
|
| 91 |
+
os.remove("@")
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/support.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support code for test_*.py files"""
|
| 2 |
+
# Author: Collin Winter
|
| 3 |
+
|
| 4 |
+
# Python imports
|
| 5 |
+
import unittest
|
| 6 |
+
import os
|
| 7 |
+
import os.path
|
| 8 |
+
from textwrap import dedent
|
| 9 |
+
|
| 10 |
+
# Local imports
|
| 11 |
+
from lib2to3 import pytree, refactor
|
| 12 |
+
from lib2to3.pgen2 import driver as pgen2_driver
|
| 13 |
+
|
| 14 |
+
test_dir = os.path.dirname(__file__)
|
| 15 |
+
proj_dir = os.path.normpath(os.path.join(test_dir, ".."))
|
| 16 |
+
grammar_path = os.path.join(test_dir, "..", "Grammar.txt")
|
| 17 |
+
grammar = pgen2_driver.load_grammar(grammar_path)
|
| 18 |
+
grammar_no_print_statement = pgen2_driver.load_grammar(grammar_path)
|
| 19 |
+
del grammar_no_print_statement.keywords["print"]
|
| 20 |
+
driver = pgen2_driver.Driver(grammar, convert=pytree.convert)
|
| 21 |
+
driver_no_print_statement = pgen2_driver.Driver(
|
| 22 |
+
grammar_no_print_statement,
|
| 23 |
+
convert=pytree.convert
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
def parse_string(string):
|
| 27 |
+
return driver.parse_string(reformat(string), debug=True)
|
| 28 |
+
|
| 29 |
+
def run_all_tests(test_mod=None, tests=None):
|
| 30 |
+
if tests is None:
|
| 31 |
+
tests = unittest.TestLoader().loadTestsFromModule(test_mod)
|
| 32 |
+
unittest.TextTestRunner(verbosity=2).run(tests)
|
| 33 |
+
|
| 34 |
+
def reformat(string):
|
| 35 |
+
return dedent(string) + "\n\n"
|
| 36 |
+
|
| 37 |
+
def get_refactorer(fixer_pkg="lib2to3", fixers=None, options=None):
|
| 38 |
+
"""
|
| 39 |
+
A convenience function for creating a RefactoringTool for tests.
|
| 40 |
+
|
| 41 |
+
fixers is a list of fixers for the RefactoringTool to use. By default
|
| 42 |
+
"lib2to3.fixes.*" is used. options is an optional dictionary of options to
|
| 43 |
+
be passed to the RefactoringTool.
|
| 44 |
+
"""
|
| 45 |
+
if fixers is not None:
|
| 46 |
+
fixers = [fixer_pkg + ".fixes.fix_" + fix for fix in fixers]
|
| 47 |
+
else:
|
| 48 |
+
fixers = refactor.get_fixers_from_package(fixer_pkg + ".fixes")
|
| 49 |
+
options = options or {}
|
| 50 |
+
return refactor.RefactoringTool(fixers, options, explicit=True)
|
| 51 |
+
|
| 52 |
+
def all_project_files():
|
| 53 |
+
for dirpath, dirnames, filenames in os.walk(proj_dir):
|
| 54 |
+
for filename in filenames:
|
| 55 |
+
if filename.endswith(".py"):
|
| 56 |
+
yield os.path.join(dirpath, filename)
|
| 57 |
+
|
| 58 |
+
TestCase = unittest.TestCase
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_all_fixers.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests that run all fixer modules over an input stream.
|
| 2 |
+
|
| 3 |
+
This has been broken out into its own test module because of its
|
| 4 |
+
running time.
|
| 5 |
+
"""
|
| 6 |
+
# Author: Collin Winter
|
| 7 |
+
|
| 8 |
+
# Python imports
|
| 9 |
+
import os.path
|
| 10 |
+
import sys
|
| 11 |
+
import test.support
|
| 12 |
+
import unittest
|
| 13 |
+
|
| 14 |
+
# Local imports
|
| 15 |
+
from . import support
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@test.support.requires_resource('cpu')
|
| 19 |
+
class Test_all(support.TestCase):
|
| 20 |
+
|
| 21 |
+
def setUp(self):
|
| 22 |
+
self.refactor = support.get_refactorer()
|
| 23 |
+
|
| 24 |
+
def refactor_file(self, filepath):
|
| 25 |
+
if test.support.verbose:
|
| 26 |
+
print(f"Refactor file: {filepath}")
|
| 27 |
+
if os.path.basename(filepath) == 'infinite_recursion.py':
|
| 28 |
+
# bpo-46542: Processing infinite_recursion.py can crash Python
|
| 29 |
+
# if Python is built in debug mode: lower the recursion limit
|
| 30 |
+
# to prevent a crash.
|
| 31 |
+
with test.support.infinite_recursion(150):
|
| 32 |
+
self.refactor.refactor_file(filepath)
|
| 33 |
+
else:
|
| 34 |
+
self.refactor.refactor_file(filepath)
|
| 35 |
+
|
| 36 |
+
def test_all_project_files(self):
|
| 37 |
+
for filepath in support.all_project_files():
|
| 38 |
+
with self.subTest(filepath=filepath):
|
| 39 |
+
self.refactor_file(filepath)
|
| 40 |
+
|
| 41 |
+
if __name__ == '__main__':
|
| 42 |
+
unittest.main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_fixers.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_main.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
import codecs
|
| 3 |
+
import io
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import shutil
|
| 8 |
+
import sys
|
| 9 |
+
import tempfile
|
| 10 |
+
import unittest
|
| 11 |
+
|
| 12 |
+
from lib2to3 import main
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
|
| 16 |
+
PY2_TEST_MODULE = os.path.join(TEST_DATA_DIR, "py2_test_grammar.py")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestMain(unittest.TestCase):
|
| 20 |
+
|
| 21 |
+
def setUp(self):
|
| 22 |
+
self.temp_dir = None # tearDown() will rmtree this directory if set.
|
| 23 |
+
|
| 24 |
+
def tearDown(self):
|
| 25 |
+
# Clean up logging configuration down by main.
|
| 26 |
+
del logging.root.handlers[:]
|
| 27 |
+
if self.temp_dir:
|
| 28 |
+
shutil.rmtree(self.temp_dir)
|
| 29 |
+
|
| 30 |
+
def run_2to3_capture(self, args, in_capture, out_capture, err_capture):
|
| 31 |
+
save_stdin = sys.stdin
|
| 32 |
+
save_stdout = sys.stdout
|
| 33 |
+
save_stderr = sys.stderr
|
| 34 |
+
sys.stdin = in_capture
|
| 35 |
+
sys.stdout = out_capture
|
| 36 |
+
sys.stderr = err_capture
|
| 37 |
+
try:
|
| 38 |
+
return main.main("lib2to3.fixes", args)
|
| 39 |
+
finally:
|
| 40 |
+
sys.stdin = save_stdin
|
| 41 |
+
sys.stdout = save_stdout
|
| 42 |
+
sys.stderr = save_stderr
|
| 43 |
+
|
| 44 |
+
def test_unencodable_diff(self):
|
| 45 |
+
input_stream = io.StringIO("print 'nothing'\nprint u'über'\n")
|
| 46 |
+
out = io.BytesIO()
|
| 47 |
+
out_enc = codecs.getwriter("ascii")(out)
|
| 48 |
+
err = io.StringIO()
|
| 49 |
+
ret = self.run_2to3_capture(["-"], input_stream, out_enc, err)
|
| 50 |
+
self.assertEqual(ret, 0)
|
| 51 |
+
output = out.getvalue().decode("ascii")
|
| 52 |
+
self.assertIn("-print 'nothing'", output)
|
| 53 |
+
self.assertIn("WARNING: couldn't encode <stdin>'s diff for "
|
| 54 |
+
"your terminal", err.getvalue())
|
| 55 |
+
|
| 56 |
+
def setup_test_source_trees(self):
|
| 57 |
+
"""Setup a test source tree and output destination tree."""
|
| 58 |
+
self.temp_dir = tempfile.mkdtemp() # tearDown() cleans this up.
|
| 59 |
+
self.py2_src_dir = os.path.join(self.temp_dir, "python2_project")
|
| 60 |
+
self.py3_dest_dir = os.path.join(self.temp_dir, "python3_project")
|
| 61 |
+
os.mkdir(self.py2_src_dir)
|
| 62 |
+
os.mkdir(self.py3_dest_dir)
|
| 63 |
+
# Turn it into a package with a few files.
|
| 64 |
+
self.setup_files = []
|
| 65 |
+
open(os.path.join(self.py2_src_dir, "__init__.py"), "w").close()
|
| 66 |
+
self.setup_files.append("__init__.py")
|
| 67 |
+
shutil.copy(PY2_TEST_MODULE, self.py2_src_dir)
|
| 68 |
+
self.setup_files.append(os.path.basename(PY2_TEST_MODULE))
|
| 69 |
+
self.trivial_py2_file = os.path.join(self.py2_src_dir, "trivial.py")
|
| 70 |
+
self.init_py2_file = os.path.join(self.py2_src_dir, "__init__.py")
|
| 71 |
+
with open(self.trivial_py2_file, "w") as trivial:
|
| 72 |
+
trivial.write("print 'I need a simple conversion.'")
|
| 73 |
+
self.setup_files.append("trivial.py")
|
| 74 |
+
|
| 75 |
+
def test_filename_changing_on_output_single_dir(self):
|
| 76 |
+
"""2to3 a single directory with a new output dir and suffix."""
|
| 77 |
+
self.setup_test_source_trees()
|
| 78 |
+
out = io.StringIO()
|
| 79 |
+
err = io.StringIO()
|
| 80 |
+
suffix = "TEST"
|
| 81 |
+
ret = self.run_2to3_capture(
|
| 82 |
+
["-n", "--add-suffix", suffix, "--write-unchanged-files",
|
| 83 |
+
"--no-diffs", "--output-dir",
|
| 84 |
+
self.py3_dest_dir, self.py2_src_dir],
|
| 85 |
+
io.StringIO(""), out, err)
|
| 86 |
+
self.assertEqual(ret, 0)
|
| 87 |
+
stderr = err.getvalue()
|
| 88 |
+
self.assertIn(" implies -w.", stderr)
|
| 89 |
+
self.assertIn(
|
| 90 |
+
"Output in %r will mirror the input directory %r layout" % (
|
| 91 |
+
self.py3_dest_dir, self.py2_src_dir), stderr)
|
| 92 |
+
self.assertEqual(set(name+suffix for name in self.setup_files),
|
| 93 |
+
set(os.listdir(self.py3_dest_dir)))
|
| 94 |
+
for name in self.setup_files:
|
| 95 |
+
self.assertIn("Writing converted %s to %s" % (
|
| 96 |
+
os.path.join(self.py2_src_dir, name),
|
| 97 |
+
os.path.join(self.py3_dest_dir, name+suffix)), stderr)
|
| 98 |
+
sep = re.escape(os.sep)
|
| 99 |
+
self.assertRegex(
|
| 100 |
+
stderr, r"No changes to .*/__init__\.py".replace("/", sep))
|
| 101 |
+
self.assertNotRegex(
|
| 102 |
+
stderr, r"No changes to .*/trivial\.py".replace("/", sep))
|
| 103 |
+
|
| 104 |
+
def test_filename_changing_on_output_two_files(self):
|
| 105 |
+
"""2to3 two files in one directory with a new output dir."""
|
| 106 |
+
self.setup_test_source_trees()
|
| 107 |
+
err = io.StringIO()
|
| 108 |
+
py2_files = [self.trivial_py2_file, self.init_py2_file]
|
| 109 |
+
expected_files = set(os.path.basename(name) for name in py2_files)
|
| 110 |
+
ret = self.run_2to3_capture(
|
| 111 |
+
["-n", "-w", "--write-unchanged-files",
|
| 112 |
+
"--no-diffs", "--output-dir", self.py3_dest_dir] + py2_files,
|
| 113 |
+
io.StringIO(""), io.StringIO(), err)
|
| 114 |
+
self.assertEqual(ret, 0)
|
| 115 |
+
stderr = err.getvalue()
|
| 116 |
+
self.assertIn(
|
| 117 |
+
"Output in %r will mirror the input directory %r layout" % (
|
| 118 |
+
self.py3_dest_dir, self.py2_src_dir), stderr)
|
| 119 |
+
self.assertEqual(expected_files, set(os.listdir(self.py3_dest_dir)))
|
| 120 |
+
|
| 121 |
+
def test_filename_changing_on_output_single_file(self):
|
| 122 |
+
"""2to3 a single file with a new output dir."""
|
| 123 |
+
self.setup_test_source_trees()
|
| 124 |
+
err = io.StringIO()
|
| 125 |
+
ret = self.run_2to3_capture(
|
| 126 |
+
["-n", "-w", "--no-diffs", "--output-dir", self.py3_dest_dir,
|
| 127 |
+
self.trivial_py2_file],
|
| 128 |
+
io.StringIO(""), io.StringIO(), err)
|
| 129 |
+
self.assertEqual(ret, 0)
|
| 130 |
+
stderr = err.getvalue()
|
| 131 |
+
self.assertIn(
|
| 132 |
+
"Output in %r will mirror the input directory %r layout" % (
|
| 133 |
+
self.py3_dest_dir, self.py2_src_dir), stderr)
|
| 134 |
+
self.assertEqual(set([os.path.basename(self.trivial_py2_file)]),
|
| 135 |
+
set(os.listdir(self.py3_dest_dir)))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
if __name__ == '__main__':
|
| 139 |
+
unittest.main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_parser.py
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test suite for 2to3's parser and grammar files.
|
| 2 |
+
|
| 3 |
+
This is the place to add tests for changes to 2to3's grammar, such as those
|
| 4 |
+
merging the grammars for Python 2 and 3. In addition to specific tests for
|
| 5 |
+
parts of the grammar we've changed, we also make sure we can parse the
|
| 6 |
+
test_grammar.py files from both Python 2 and Python 3.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
# Testing imports
|
| 10 |
+
from . import support
|
| 11 |
+
from .support import driver, driver_no_print_statement
|
| 12 |
+
|
| 13 |
+
# Python imports
|
| 14 |
+
import difflib
|
| 15 |
+
import importlib
|
| 16 |
+
import operator
|
| 17 |
+
import os
|
| 18 |
+
import pickle
|
| 19 |
+
import shutil
|
| 20 |
+
import subprocess
|
| 21 |
+
import sys
|
| 22 |
+
import tempfile
|
| 23 |
+
import test.support
|
| 24 |
+
import unittest
|
| 25 |
+
|
| 26 |
+
# Local imports
|
| 27 |
+
from lib2to3.pgen2 import driver as pgen2_driver
|
| 28 |
+
from lib2to3.pgen2 import tokenize
|
| 29 |
+
from ..pgen2.parse import ParseError
|
| 30 |
+
from lib2to3.pygram import python_symbols as syms
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TestDriver(support.TestCase):
|
| 34 |
+
|
| 35 |
+
def test_formfeed(self):
|
| 36 |
+
s = """print 1\n\x0Cprint 2\n"""
|
| 37 |
+
t = driver.parse_string(s)
|
| 38 |
+
self.assertEqual(t.children[0].children[0].type, syms.print_stmt)
|
| 39 |
+
self.assertEqual(t.children[1].children[0].type, syms.print_stmt)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class TestPgen2Caching(support.TestCase):
|
| 43 |
+
def test_load_grammar_from_txt_file(self):
|
| 44 |
+
pgen2_driver.load_grammar(support.grammar_path, save=False, force=True)
|
| 45 |
+
|
| 46 |
+
def test_load_grammar_from_pickle(self):
|
| 47 |
+
# Make a copy of the grammar file in a temp directory we are
|
| 48 |
+
# guaranteed to be able to write to.
|
| 49 |
+
tmpdir = tempfile.mkdtemp()
|
| 50 |
+
try:
|
| 51 |
+
grammar_copy = os.path.join(
|
| 52 |
+
tmpdir, os.path.basename(support.grammar_path))
|
| 53 |
+
shutil.copy(support.grammar_path, grammar_copy)
|
| 54 |
+
pickle_name = pgen2_driver._generate_pickle_name(grammar_copy)
|
| 55 |
+
|
| 56 |
+
pgen2_driver.load_grammar(grammar_copy, save=True, force=True)
|
| 57 |
+
self.assertTrue(os.path.exists(pickle_name))
|
| 58 |
+
|
| 59 |
+
os.unlink(grammar_copy) # Only the pickle remains...
|
| 60 |
+
pgen2_driver.load_grammar(grammar_copy, save=False, force=False)
|
| 61 |
+
finally:
|
| 62 |
+
shutil.rmtree(tmpdir)
|
| 63 |
+
|
| 64 |
+
@unittest.skipIf(sys.executable is None, 'sys.executable required')
|
| 65 |
+
def test_load_grammar_from_subprocess(self):
|
| 66 |
+
tmpdir = tempfile.mkdtemp()
|
| 67 |
+
tmpsubdir = os.path.join(tmpdir, 'subdir')
|
| 68 |
+
try:
|
| 69 |
+
os.mkdir(tmpsubdir)
|
| 70 |
+
grammar_base = os.path.basename(support.grammar_path)
|
| 71 |
+
grammar_copy = os.path.join(tmpdir, grammar_base)
|
| 72 |
+
grammar_sub_copy = os.path.join(tmpsubdir, grammar_base)
|
| 73 |
+
shutil.copy(support.grammar_path, grammar_copy)
|
| 74 |
+
shutil.copy(support.grammar_path, grammar_sub_copy)
|
| 75 |
+
pickle_name = pgen2_driver._generate_pickle_name(grammar_copy)
|
| 76 |
+
pickle_sub_name = pgen2_driver._generate_pickle_name(
|
| 77 |
+
grammar_sub_copy)
|
| 78 |
+
self.assertNotEqual(pickle_name, pickle_sub_name)
|
| 79 |
+
|
| 80 |
+
# Generate a pickle file from this process.
|
| 81 |
+
pgen2_driver.load_grammar(grammar_copy, save=True, force=True)
|
| 82 |
+
self.assertTrue(os.path.exists(pickle_name))
|
| 83 |
+
|
| 84 |
+
# Generate a new pickle file in a subprocess with a most likely
|
| 85 |
+
# different hash randomization seed.
|
| 86 |
+
sub_env = dict(os.environ)
|
| 87 |
+
sub_env['PYTHONHASHSEED'] = 'random'
|
| 88 |
+
code = """
|
| 89 |
+
from lib2to3.pgen2 import driver as pgen2_driver
|
| 90 |
+
pgen2_driver.load_grammar(%r, save=True, force=True)
|
| 91 |
+
""" % (grammar_sub_copy,)
|
| 92 |
+
msg = ("lib2to3 package is deprecated and may not be able "
|
| 93 |
+
"to parse Python 3.10+")
|
| 94 |
+
cmd = [sys.executable,
|
| 95 |
+
f'-Wignore:{msg}:PendingDeprecationWarning',
|
| 96 |
+
'-c', code]
|
| 97 |
+
subprocess.check_call( cmd, env=sub_env)
|
| 98 |
+
self.assertTrue(os.path.exists(pickle_sub_name))
|
| 99 |
+
|
| 100 |
+
with open(pickle_name, 'rb') as pickle_f_1, \
|
| 101 |
+
open(pickle_sub_name, 'rb') as pickle_f_2:
|
| 102 |
+
self.assertEqual(
|
| 103 |
+
pickle_f_1.read(), pickle_f_2.read(),
|
| 104 |
+
msg='Grammar caches generated using different hash seeds'
|
| 105 |
+
' were not identical.')
|
| 106 |
+
finally:
|
| 107 |
+
shutil.rmtree(tmpdir)
|
| 108 |
+
|
| 109 |
+
def test_load_packaged_grammar(self):
|
| 110 |
+
modname = __name__ + '.load_test'
|
| 111 |
+
class MyLoader:
|
| 112 |
+
def get_data(self, where):
|
| 113 |
+
return pickle.dumps({'elephant': 19})
|
| 114 |
+
class MyModule:
|
| 115 |
+
__file__ = 'parsertestmodule'
|
| 116 |
+
__spec__ = importlib.util.spec_from_loader(modname, MyLoader())
|
| 117 |
+
sys.modules[modname] = MyModule()
|
| 118 |
+
self.addCleanup(operator.delitem, sys.modules, modname)
|
| 119 |
+
g = pgen2_driver.load_packaged_grammar(modname, 'Grammar.txt')
|
| 120 |
+
self.assertEqual(g.elephant, 19)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class GrammarTest(support.TestCase):
|
| 124 |
+
def validate(self, code):
|
| 125 |
+
support.parse_string(code)
|
| 126 |
+
|
| 127 |
+
def invalid_syntax(self, code):
|
| 128 |
+
try:
|
| 129 |
+
self.validate(code)
|
| 130 |
+
except ParseError:
|
| 131 |
+
pass
|
| 132 |
+
else:
|
| 133 |
+
raise AssertionError("Syntax shouldn't have been valid")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TestMatrixMultiplication(GrammarTest):
|
| 137 |
+
def test_matrix_multiplication_operator(self):
|
| 138 |
+
self.validate("a @ b")
|
| 139 |
+
self.validate("a @= b")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class TestYieldFrom(GrammarTest):
|
| 143 |
+
def test_yield_from(self):
|
| 144 |
+
self.validate("yield from x")
|
| 145 |
+
self.validate("(yield from x) + y")
|
| 146 |
+
self.invalid_syntax("yield from")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class TestAsyncAwait(GrammarTest):
|
| 150 |
+
def test_await_expr(self):
|
| 151 |
+
self.validate("""async def foo():
|
| 152 |
+
await x
|
| 153 |
+
""")
|
| 154 |
+
|
| 155 |
+
self.validate("""async def foo():
|
| 156 |
+
[i async for i in b]
|
| 157 |
+
""")
|
| 158 |
+
|
| 159 |
+
self.validate("""async def foo():
|
| 160 |
+
{i for i in b
|
| 161 |
+
async for i in a if await i
|
| 162 |
+
for b in i}
|
| 163 |
+
""")
|
| 164 |
+
|
| 165 |
+
self.validate("""async def foo():
|
| 166 |
+
[await i for i in b if await c]
|
| 167 |
+
""")
|
| 168 |
+
|
| 169 |
+
self.validate("""async def foo():
|
| 170 |
+
[ i for i in b if c]
|
| 171 |
+
""")
|
| 172 |
+
|
| 173 |
+
self.validate("""async def foo():
|
| 174 |
+
|
| 175 |
+
def foo(): pass
|
| 176 |
+
|
| 177 |
+
def foo(): pass
|
| 178 |
+
|
| 179 |
+
await x
|
| 180 |
+
""")
|
| 181 |
+
|
| 182 |
+
self.validate("""async def foo(): return await a""")
|
| 183 |
+
|
| 184 |
+
self.validate("""def foo():
|
| 185 |
+
def foo(): pass
|
| 186 |
+
async def foo(): await x
|
| 187 |
+
""")
|
| 188 |
+
|
| 189 |
+
self.invalid_syntax("await x")
|
| 190 |
+
self.invalid_syntax("""def foo():
|
| 191 |
+
await x""")
|
| 192 |
+
|
| 193 |
+
self.invalid_syntax("""def foo():
|
| 194 |
+
def foo(): pass
|
| 195 |
+
async def foo(): pass
|
| 196 |
+
await x
|
| 197 |
+
""")
|
| 198 |
+
|
| 199 |
+
def test_async_var(self):
|
| 200 |
+
self.validate("""async = 1""")
|
| 201 |
+
self.validate("""await = 1""")
|
| 202 |
+
self.validate("""def async(): pass""")
|
| 203 |
+
|
| 204 |
+
def test_async_for(self):
|
| 205 |
+
self.validate("""async def foo():
|
| 206 |
+
async for a in b: pass""")
|
| 207 |
+
|
| 208 |
+
def test_async_with(self):
|
| 209 |
+
self.validate("""async def foo():
|
| 210 |
+
async with a: pass""")
|
| 211 |
+
|
| 212 |
+
self.invalid_syntax("""def foo():
|
| 213 |
+
async with a: pass""")
|
| 214 |
+
|
| 215 |
+
def test_async_generator(self):
|
| 216 |
+
self.validate(
|
| 217 |
+
"""async def foo():
|
| 218 |
+
return (i * 2 async for i in arange(42))"""
|
| 219 |
+
)
|
| 220 |
+
self.validate(
|
| 221 |
+
"""def foo():
|
| 222 |
+
return (i * 2 async for i in arange(42))"""
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
class TestRaiseChanges(GrammarTest):
|
| 227 |
+
def test_2x_style_1(self):
|
| 228 |
+
self.validate("raise")
|
| 229 |
+
|
| 230 |
+
def test_2x_style_2(self):
|
| 231 |
+
self.validate("raise E, V")
|
| 232 |
+
|
| 233 |
+
def test_2x_style_3(self):
|
| 234 |
+
self.validate("raise E, V, T")
|
| 235 |
+
|
| 236 |
+
def test_2x_style_invalid_1(self):
|
| 237 |
+
self.invalid_syntax("raise E, V, T, Z")
|
| 238 |
+
|
| 239 |
+
def test_3x_style(self):
|
| 240 |
+
self.validate("raise E1 from E2")
|
| 241 |
+
|
| 242 |
+
def test_3x_style_invalid_1(self):
|
| 243 |
+
self.invalid_syntax("raise E, V from E1")
|
| 244 |
+
|
| 245 |
+
def test_3x_style_invalid_2(self):
|
| 246 |
+
self.invalid_syntax("raise E from E1, E2")
|
| 247 |
+
|
| 248 |
+
def test_3x_style_invalid_3(self):
|
| 249 |
+
self.invalid_syntax("raise from E1, E2")
|
| 250 |
+
|
| 251 |
+
def test_3x_style_invalid_4(self):
|
| 252 |
+
self.invalid_syntax("raise E from")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# Modelled after Lib/test/test_grammar.py:TokenTests.test_funcdef issue2292
|
| 256 |
+
# and Lib/test/text_parser.py test_list_displays, test_set_displays,
|
| 257 |
+
# test_dict_displays, test_argument_unpacking, ... changes.
|
| 258 |
+
class TestUnpackingGeneralizations(GrammarTest):
|
| 259 |
+
def test_mid_positional_star(self):
|
| 260 |
+
self.validate("""func(1, *(2, 3), 4)""")
|
| 261 |
+
|
| 262 |
+
def test_double_star_dict_literal(self):
|
| 263 |
+
self.validate("""func(**{'eggs':'scrambled', 'spam':'fried'})""")
|
| 264 |
+
|
| 265 |
+
def test_double_star_dict_literal_after_keywords(self):
|
| 266 |
+
self.validate("""func(spam='fried', **{'eggs':'scrambled'})""")
|
| 267 |
+
|
| 268 |
+
def test_double_star_expression(self):
|
| 269 |
+
self.validate("""func(**{'a':2} or {})""")
|
| 270 |
+
self.validate("""func(**() or {})""")
|
| 271 |
+
|
| 272 |
+
def test_star_expression(self):
|
| 273 |
+
self.validate("""func(*[] or [2])""")
|
| 274 |
+
|
| 275 |
+
def test_list_display(self):
|
| 276 |
+
self.validate("""[*{2}, 3, *[4]]""")
|
| 277 |
+
|
| 278 |
+
def test_set_display(self):
|
| 279 |
+
self.validate("""{*{2}, 3, *[4]}""")
|
| 280 |
+
|
| 281 |
+
def test_dict_display_1(self):
|
| 282 |
+
self.validate("""{**{}}""")
|
| 283 |
+
|
| 284 |
+
def test_dict_display_2(self):
|
| 285 |
+
self.validate("""{**{}, 3:4, **{5:6, 7:8}}""")
|
| 286 |
+
|
| 287 |
+
def test_complex_star_expression(self):
|
| 288 |
+
self.validate("func(* [] or [1])")
|
| 289 |
+
|
| 290 |
+
def test_complex_double_star_expression(self):
|
| 291 |
+
self.validate("func(**{1: 3} if False else {x: x for x in range(3)})")
|
| 292 |
+
|
| 293 |
+
def test_argument_unpacking_1(self):
|
| 294 |
+
self.validate("""f(a, *b, *c, d)""")
|
| 295 |
+
|
| 296 |
+
def test_argument_unpacking_2(self):
|
| 297 |
+
self.validate("""f(**a, **b)""")
|
| 298 |
+
|
| 299 |
+
def test_argument_unpacking_3(self):
|
| 300 |
+
self.validate("""f(2, *a, *b, **b, **c, **d)""")
|
| 301 |
+
|
| 302 |
+
def test_trailing_commas_1(self):
|
| 303 |
+
self.validate("def f(a, b): call(a, b)")
|
| 304 |
+
self.validate("def f(a, b,): call(a, b,)")
|
| 305 |
+
|
| 306 |
+
def test_trailing_commas_2(self):
|
| 307 |
+
self.validate("def f(a, *b): call(a, *b)")
|
| 308 |
+
self.validate("def f(a, *b,): call(a, *b,)")
|
| 309 |
+
|
| 310 |
+
def test_trailing_commas_3(self):
|
| 311 |
+
self.validate("def f(a, b=1): call(a, b=1)")
|
| 312 |
+
self.validate("def f(a, b=1,): call(a, b=1,)")
|
| 313 |
+
|
| 314 |
+
def test_trailing_commas_4(self):
|
| 315 |
+
self.validate("def f(a, **b): call(a, **b)")
|
| 316 |
+
self.validate("def f(a, **b,): call(a, **b,)")
|
| 317 |
+
|
| 318 |
+
def test_trailing_commas_5(self):
|
| 319 |
+
self.validate("def f(*a, b=1): call(*a, b=1)")
|
| 320 |
+
self.validate("def f(*a, b=1,): call(*a, b=1,)")
|
| 321 |
+
|
| 322 |
+
def test_trailing_commas_6(self):
|
| 323 |
+
self.validate("def f(*a, **b): call(*a, **b)")
|
| 324 |
+
self.validate("def f(*a, **b,): call(*a, **b,)")
|
| 325 |
+
|
| 326 |
+
def test_trailing_commas_7(self):
|
| 327 |
+
self.validate("def f(*, b=1): call(*b)")
|
| 328 |
+
self.validate("def f(*, b=1,): call(*b,)")
|
| 329 |
+
|
| 330 |
+
def test_trailing_commas_8(self):
|
| 331 |
+
self.validate("def f(a=1, b=2): call(a=1, b=2)")
|
| 332 |
+
self.validate("def f(a=1, b=2,): call(a=1, b=2,)")
|
| 333 |
+
|
| 334 |
+
def test_trailing_commas_9(self):
|
| 335 |
+
self.validate("def f(a=1, **b): call(a=1, **b)")
|
| 336 |
+
self.validate("def f(a=1, **b,): call(a=1, **b,)")
|
| 337 |
+
|
| 338 |
+
def test_trailing_commas_lambda_1(self):
|
| 339 |
+
self.validate("f = lambda a, b: call(a, b)")
|
| 340 |
+
self.validate("f = lambda a, b,: call(a, b,)")
|
| 341 |
+
|
| 342 |
+
def test_trailing_commas_lambda_2(self):
|
| 343 |
+
self.validate("f = lambda a, *b: call(a, *b)")
|
| 344 |
+
self.validate("f = lambda a, *b,: call(a, *b,)")
|
| 345 |
+
|
| 346 |
+
def test_trailing_commas_lambda_3(self):
|
| 347 |
+
self.validate("f = lambda a, b=1: call(a, b=1)")
|
| 348 |
+
self.validate("f = lambda a, b=1,: call(a, b=1,)")
|
| 349 |
+
|
| 350 |
+
def test_trailing_commas_lambda_4(self):
|
| 351 |
+
self.validate("f = lambda a, **b: call(a, **b)")
|
| 352 |
+
self.validate("f = lambda a, **b,: call(a, **b,)")
|
| 353 |
+
|
| 354 |
+
def test_trailing_commas_lambda_5(self):
|
| 355 |
+
self.validate("f = lambda *a, b=1: call(*a, b=1)")
|
| 356 |
+
self.validate("f = lambda *a, b=1,: call(*a, b=1,)")
|
| 357 |
+
|
| 358 |
+
def test_trailing_commas_lambda_6(self):
|
| 359 |
+
self.validate("f = lambda *a, **b: call(*a, **b)")
|
| 360 |
+
self.validate("f = lambda *a, **b,: call(*a, **b,)")
|
| 361 |
+
|
| 362 |
+
def test_trailing_commas_lambda_7(self):
|
| 363 |
+
self.validate("f = lambda *, b=1: call(*b)")
|
| 364 |
+
self.validate("f = lambda *, b=1,: call(*b,)")
|
| 365 |
+
|
| 366 |
+
def test_trailing_commas_lambda_8(self):
|
| 367 |
+
self.validate("f = lambda a=1, b=2: call(a=1, b=2)")
|
| 368 |
+
self.validate("f = lambda a=1, b=2,: call(a=1, b=2,)")
|
| 369 |
+
|
| 370 |
+
def test_trailing_commas_lambda_9(self):
|
| 371 |
+
self.validate("f = lambda a=1, **b: call(a=1, **b)")
|
| 372 |
+
self.validate("f = lambda a=1, **b,: call(a=1, **b,)")
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
|
| 376 |
+
class TestFunctionAnnotations(GrammarTest):
|
| 377 |
+
def test_1(self):
|
| 378 |
+
self.validate("""def f(x) -> list: pass""")
|
| 379 |
+
|
| 380 |
+
def test_2(self):
|
| 381 |
+
self.validate("""def f(x:int): pass""")
|
| 382 |
+
|
| 383 |
+
def test_3(self):
|
| 384 |
+
self.validate("""def f(*x:str): pass""")
|
| 385 |
+
|
| 386 |
+
def test_4(self):
|
| 387 |
+
self.validate("""def f(**x:float): pass""")
|
| 388 |
+
|
| 389 |
+
def test_5(self):
|
| 390 |
+
self.validate("""def f(x, y:1+2): pass""")
|
| 391 |
+
|
| 392 |
+
def test_6(self):
|
| 393 |
+
self.validate("""def f(a, (b:1, c:2, d)): pass""")
|
| 394 |
+
|
| 395 |
+
def test_7(self):
|
| 396 |
+
self.validate("""def f(a, (b:1, c:2, d), e:3=4, f=5, *g:6): pass""")
|
| 397 |
+
|
| 398 |
+
def test_8(self):
|
| 399 |
+
s = """def f(a, (b:1, c:2, d), e:3=4, f=5,
|
| 400 |
+
*g:6, h:7, i=8, j:9=10, **k:11) -> 12: pass"""
|
| 401 |
+
self.validate(s)
|
| 402 |
+
|
| 403 |
+
def test_9(self):
|
| 404 |
+
s = """def f(
|
| 405 |
+
a: str,
|
| 406 |
+
b: int,
|
| 407 |
+
*,
|
| 408 |
+
c: bool = False,
|
| 409 |
+
**kwargs,
|
| 410 |
+
) -> None:
|
| 411 |
+
call(c=c, **kwargs,)"""
|
| 412 |
+
self.validate(s)
|
| 413 |
+
|
| 414 |
+
def test_10(self):
|
| 415 |
+
s = """def f(
|
| 416 |
+
a: str,
|
| 417 |
+
) -> None:
|
| 418 |
+
call(a,)"""
|
| 419 |
+
self.validate(s)
|
| 420 |
+
|
| 421 |
+
def test_11(self):
|
| 422 |
+
s = """def f(
|
| 423 |
+
a: str = '',
|
| 424 |
+
) -> None:
|
| 425 |
+
call(a=a,)"""
|
| 426 |
+
self.validate(s)
|
| 427 |
+
|
| 428 |
+
def test_12(self):
|
| 429 |
+
s = """def f(
|
| 430 |
+
*args: str,
|
| 431 |
+
) -> None:
|
| 432 |
+
call(*args,)"""
|
| 433 |
+
self.validate(s)
|
| 434 |
+
|
| 435 |
+
def test_13(self):
|
| 436 |
+
self.validate("def f(a: str, b: int) -> None: call(a, b)")
|
| 437 |
+
self.validate("def f(a: str, b: int,) -> None: call(a, b,)")
|
| 438 |
+
|
| 439 |
+
def test_14(self):
|
| 440 |
+
self.validate("def f(a: str, *b: int) -> None: call(a, *b)")
|
| 441 |
+
self.validate("def f(a: str, *b: int,) -> None: call(a, *b,)")
|
| 442 |
+
|
| 443 |
+
def test_15(self):
|
| 444 |
+
self.validate("def f(a: str, b: int=1) -> None: call(a, b=1)")
|
| 445 |
+
self.validate("def f(a: str, b: int=1,) -> None: call(a, b=1,)")
|
| 446 |
+
|
| 447 |
+
def test_16(self):
|
| 448 |
+
self.validate("def f(a: str, **b: int) -> None: call(a, **b)")
|
| 449 |
+
self.validate("def f(a: str, **b: int,) -> None: call(a, **b,)")
|
| 450 |
+
|
| 451 |
+
def test_17(self):
|
| 452 |
+
self.validate("def f(*a: str, b: int=1) -> None: call(*a, b=1)")
|
| 453 |
+
self.validate("def f(*a: str, b: int=1,) -> None: call(*a, b=1,)")
|
| 454 |
+
|
| 455 |
+
def test_18(self):
|
| 456 |
+
self.validate("def f(*a: str, **b: int) -> None: call(*a, **b)")
|
| 457 |
+
self.validate("def f(*a: str, **b: int,) -> None: call(*a, **b,)")
|
| 458 |
+
|
| 459 |
+
def test_19(self):
|
| 460 |
+
self.validate("def f(*, b: int=1) -> None: call(*b)")
|
| 461 |
+
self.validate("def f(*, b: int=1,) -> None: call(*b,)")
|
| 462 |
+
|
| 463 |
+
def test_20(self):
|
| 464 |
+
self.validate("def f(a: str='', b: int=2) -> None: call(a=a, b=2)")
|
| 465 |
+
self.validate("def f(a: str='', b: int=2,) -> None: call(a=a, b=2,)")
|
| 466 |
+
|
| 467 |
+
def test_21(self):
|
| 468 |
+
self.validate("def f(a: str='', **b: int) -> None: call(a=a, **b)")
|
| 469 |
+
self.validate("def f(a: str='', **b: int,) -> None: call(a=a, **b,)")
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
# Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.test_var_annot
|
| 473 |
+
class TestVarAnnotations(GrammarTest):
|
| 474 |
+
def test_1(self):
|
| 475 |
+
self.validate("var1: int = 5")
|
| 476 |
+
|
| 477 |
+
def test_2(self):
|
| 478 |
+
self.validate("var2: [int, str]")
|
| 479 |
+
|
| 480 |
+
def test_3(self):
|
| 481 |
+
self.validate("def f():\n"
|
| 482 |
+
" st: str = 'Hello'\n"
|
| 483 |
+
" a.b: int = (1, 2)\n"
|
| 484 |
+
" return st\n")
|
| 485 |
+
|
| 486 |
+
def test_4(self):
|
| 487 |
+
self.validate("def fbad():\n"
|
| 488 |
+
" x: int\n"
|
| 489 |
+
" print(x)\n")
|
| 490 |
+
|
| 491 |
+
def test_5(self):
|
| 492 |
+
self.validate("class C:\n"
|
| 493 |
+
" x: int\n"
|
| 494 |
+
" s: str = 'attr'\n"
|
| 495 |
+
" z = 2\n"
|
| 496 |
+
" def __init__(self, x):\n"
|
| 497 |
+
" self.x: int = x\n")
|
| 498 |
+
|
| 499 |
+
def test_6(self):
|
| 500 |
+
self.validate("lst: List[int] = []")
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class TestExcept(GrammarTest):
|
| 504 |
+
def test_new(self):
|
| 505 |
+
s = """
|
| 506 |
+
try:
|
| 507 |
+
x
|
| 508 |
+
except E as N:
|
| 509 |
+
y"""
|
| 510 |
+
self.validate(s)
|
| 511 |
+
|
| 512 |
+
def test_old(self):
|
| 513 |
+
s = """
|
| 514 |
+
try:
|
| 515 |
+
x
|
| 516 |
+
except E, N:
|
| 517 |
+
y"""
|
| 518 |
+
self.validate(s)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class TestStringLiterals(GrammarTest):
|
| 522 |
+
prefixes = ("'", '"',
|
| 523 |
+
"r'", 'r"', "R'", 'R"',
|
| 524 |
+
"u'", 'u"', "U'", 'U"',
|
| 525 |
+
"b'", 'b"', "B'", 'B"',
|
| 526 |
+
"f'", 'f"', "F'", 'F"',
|
| 527 |
+
"ur'", 'ur"', "Ur'", 'Ur"',
|
| 528 |
+
"uR'", 'uR"', "UR'", 'UR"',
|
| 529 |
+
"br'", 'br"', "Br'", 'Br"',
|
| 530 |
+
"bR'", 'bR"', "BR'", 'BR"',
|
| 531 |
+
"rb'", 'rb"', "Rb'", 'Rb"',
|
| 532 |
+
"rB'", 'rB"', "RB'", 'RB"',)
|
| 533 |
+
|
| 534 |
+
def test_lit(self):
|
| 535 |
+
for pre in self.prefixes:
|
| 536 |
+
single = "{p}spamspamspam{s}".format(p=pre, s=pre[-1])
|
| 537 |
+
self.validate(single)
|
| 538 |
+
triple = "{p}{s}{s}eggs{s}{s}{s}".format(p=pre, s=pre[-1])
|
| 539 |
+
self.validate(triple)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
# Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testAtoms
|
| 543 |
+
class TestSetLiteral(GrammarTest):
|
| 544 |
+
def test_1(self):
|
| 545 |
+
self.validate("""x = {'one'}""")
|
| 546 |
+
|
| 547 |
+
def test_2(self):
|
| 548 |
+
self.validate("""x = {'one', 1,}""")
|
| 549 |
+
|
| 550 |
+
def test_3(self):
|
| 551 |
+
self.validate("""x = {'one', 'two', 'three'}""")
|
| 552 |
+
|
| 553 |
+
def test_4(self):
|
| 554 |
+
self.validate("""x = {2, 3, 4,}""")
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
# Adapted from Python 3's Lib/test/test_unicode_identifiers.py and
|
| 558 |
+
# Lib/test/test_tokenize.py:TokenizeTest.test_non_ascii_identifiers
|
| 559 |
+
class TestIdentifier(GrammarTest):
|
| 560 |
+
def test_non_ascii_identifiers(self):
|
| 561 |
+
self.validate("Örter = 'places'\ngrün = 'green'")
|
| 562 |
+
self.validate("蟒 = a蟒 = 锦蛇 = 1")
|
| 563 |
+
self.validate("µ = aµ = µµ = 1")
|
| 564 |
+
self.validate("𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = a_𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = 1")
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class TestNumericLiterals(GrammarTest):
|
| 568 |
+
def test_new_octal_notation(self):
|
| 569 |
+
self.validate("""0o7777777777777""")
|
| 570 |
+
self.invalid_syntax("""0o7324528887""")
|
| 571 |
+
|
| 572 |
+
def test_new_binary_notation(self):
|
| 573 |
+
self.validate("""0b101010""")
|
| 574 |
+
self.invalid_syntax("""0b0101021""")
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class TestClassDef(GrammarTest):
|
| 578 |
+
def test_new_syntax(self):
|
| 579 |
+
self.validate("class B(t=7): pass")
|
| 580 |
+
self.validate("class B(t, *args): pass")
|
| 581 |
+
self.validate("class B(t, **kwargs): pass")
|
| 582 |
+
self.validate("class B(t, *args, **kwargs): pass")
|
| 583 |
+
self.validate("class B(t, y=9, *args, **kwargs,): pass")
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class TestParserIdempotency(support.TestCase):
|
| 587 |
+
|
| 588 |
+
"""A cut-down version of pytree_idempotency.py."""
|
| 589 |
+
|
| 590 |
+
def parse_file(self, filepath):
|
| 591 |
+
if test.support.verbose:
|
| 592 |
+
print(f"Parse file: {filepath}")
|
| 593 |
+
with open(filepath, "rb") as fp:
|
| 594 |
+
encoding = tokenize.detect_encoding(fp.readline)[0]
|
| 595 |
+
self.assertIsNotNone(encoding,
|
| 596 |
+
"can't detect encoding for %s" % filepath)
|
| 597 |
+
with open(filepath, "r", encoding=encoding) as fp:
|
| 598 |
+
source = fp.read()
|
| 599 |
+
try:
|
| 600 |
+
tree = driver.parse_string(source)
|
| 601 |
+
except ParseError:
|
| 602 |
+
try:
|
| 603 |
+
tree = driver_no_print_statement.parse_string(source)
|
| 604 |
+
except ParseError as err:
|
| 605 |
+
self.fail('ParseError on file %s (%s)' % (filepath, err))
|
| 606 |
+
new = str(tree)
|
| 607 |
+
if new != source:
|
| 608 |
+
print(diff_texts(source, new, filepath))
|
| 609 |
+
self.fail("Idempotency failed: %s" % filepath)
|
| 610 |
+
|
| 611 |
+
def test_all_project_files(self):
|
| 612 |
+
for filepath in support.all_project_files():
|
| 613 |
+
with self.subTest(filepath=filepath):
|
| 614 |
+
self.parse_file(filepath)
|
| 615 |
+
|
| 616 |
+
def test_extended_unpacking(self):
|
| 617 |
+
driver.parse_string("a, *b, c = x\n")
|
| 618 |
+
driver.parse_string("[*a, b] = x\n")
|
| 619 |
+
driver.parse_string("(z, *y, w) = m\n")
|
| 620 |
+
driver.parse_string("for *z, m in d: pass\n")
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class TestLiterals(GrammarTest):
|
| 624 |
+
|
| 625 |
+
def validate(self, s):
|
| 626 |
+
driver.parse_string(support.dedent(s) + "\n\n")
|
| 627 |
+
|
| 628 |
+
def test_multiline_bytes_literals(self):
|
| 629 |
+
s = """
|
| 630 |
+
md5test(b"\xaa" * 80,
|
| 631 |
+
(b"Test Using Larger Than Block-Size Key "
|
| 632 |
+
b"and Larger Than One Block-Size Data"),
|
| 633 |
+
"6f630fad67cda0ee1fb1f562db3aa53e")
|
| 634 |
+
"""
|
| 635 |
+
self.validate(s)
|
| 636 |
+
|
| 637 |
+
def test_multiline_bytes_tripquote_literals(self):
|
| 638 |
+
s = '''
|
| 639 |
+
b"""
|
| 640 |
+
<?xml version="1.0" encoding="UTF-8"?>
|
| 641 |
+
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN">
|
| 642 |
+
"""
|
| 643 |
+
'''
|
| 644 |
+
self.validate(s)
|
| 645 |
+
|
| 646 |
+
def test_multiline_str_literals(self):
|
| 647 |
+
s = """
|
| 648 |
+
md5test("\xaa" * 80,
|
| 649 |
+
("Test Using Larger Than Block-Size Key "
|
| 650 |
+
"and Larger Than One Block-Size Data"),
|
| 651 |
+
"6f630fad67cda0ee1fb1f562db3aa53e")
|
| 652 |
+
"""
|
| 653 |
+
self.validate(s)
|
| 654 |
+
|
| 655 |
+
|
| 656 |
+
class TestNamedAssignments(GrammarTest):
|
| 657 |
+
"""Also known as the walrus operator."""
|
| 658 |
+
|
| 659 |
+
def test_named_assignment_if(self):
|
| 660 |
+
driver.parse_string("if f := x(): pass\n")
|
| 661 |
+
|
| 662 |
+
def test_named_assignment_while(self):
|
| 663 |
+
driver.parse_string("while f := x(): pass\n")
|
| 664 |
+
|
| 665 |
+
def test_named_assignment_generator(self):
|
| 666 |
+
driver.parse_string("any((lastNum := num) == 1 for num in [1, 2, 3])\n")
|
| 667 |
+
|
| 668 |
+
def test_named_assignment_listcomp(self):
|
| 669 |
+
driver.parse_string("[(lastNum := num) == 1 for num in [1, 2, 3]]\n")
|
| 670 |
+
|
| 671 |
+
|
| 672 |
+
class TestPositionalOnlyArgs(GrammarTest):
|
| 673 |
+
|
| 674 |
+
def test_one_pos_only_arg(self):
|
| 675 |
+
driver.parse_string("def one_pos_only_arg(a, /): pass\n")
|
| 676 |
+
|
| 677 |
+
def test_all_markers(self):
|
| 678 |
+
driver.parse_string(
|
| 679 |
+
"def all_markers(a, b=2, /, c, d=4, *, e=5, f): pass\n")
|
| 680 |
+
|
| 681 |
+
def test_all_with_args_and_kwargs(self):
|
| 682 |
+
driver.parse_string(
|
| 683 |
+
"""def all_markers_with_args_and_kwargs(
|
| 684 |
+
aa, b, /, _cc, d, *args, e, f_f, **kwargs,
|
| 685 |
+
):
|
| 686 |
+
pass\n""")
|
| 687 |
+
|
| 688 |
+
def test_lambda_soup(self):
|
| 689 |
+
driver.parse_string(
|
| 690 |
+
"lambda a, b, /, c, d, *args, e, f, **kw: kw\n")
|
| 691 |
+
|
| 692 |
+
def test_only_positional_or_keyword(self):
|
| 693 |
+
driver.parse_string("def func(a,b,/,*,g,e=3): pass\n")
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
class TestPickleableException(unittest.TestCase):
|
| 697 |
+
def test_ParseError(self):
|
| 698 |
+
err = ParseError('msg', 2, None, (1, 'context'))
|
| 699 |
+
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
|
| 700 |
+
err2 = pickle.loads(pickle.dumps(err, protocol=proto))
|
| 701 |
+
self.assertEqual(err.args, err2.args)
|
| 702 |
+
self.assertEqual(err.msg, err2.msg)
|
| 703 |
+
self.assertEqual(err.type, err2.type)
|
| 704 |
+
self.assertEqual(err.value, err2.value)
|
| 705 |
+
self.assertEqual(err.context, err2.context)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def diff_texts(a, b, filename):
|
| 709 |
+
a = a.splitlines()
|
| 710 |
+
b = b.splitlines()
|
| 711 |
+
return difflib.unified_diff(a, b, filename, filename,
|
| 712 |
+
"(original)", "(reserialized)",
|
| 713 |
+
lineterm="")
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
if __name__ == '__main__':
|
| 717 |
+
unittest.main()
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_pytree.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2006 Google, Inc. All Rights Reserved.
|
| 2 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 3 |
+
|
| 4 |
+
"""Unit tests for pytree.py.
|
| 5 |
+
|
| 6 |
+
NOTE: Please *don't* add doc strings to individual test methods!
|
| 7 |
+
In verbose mode, printing of the module, class and method name is much
|
| 8 |
+
more helpful than printing of (the first line of) the docstring,
|
| 9 |
+
especially when debugging a test.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
# Testing imports
|
| 13 |
+
from . import support
|
| 14 |
+
|
| 15 |
+
from lib2to3 import pytree
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
sorted
|
| 19 |
+
except NameError:
|
| 20 |
+
def sorted(lst):
|
| 21 |
+
l = list(lst)
|
| 22 |
+
l.sort()
|
| 23 |
+
return l
|
| 24 |
+
|
| 25 |
+
class TestNodes(support.TestCase):
|
| 26 |
+
|
| 27 |
+
"""Unit tests for nodes (Base, Leaf, Node)."""
|
| 28 |
+
|
| 29 |
+
def test_instantiate_base(self):
|
| 30 |
+
if __debug__:
|
| 31 |
+
# Test that instantiating Base() raises an AssertionError
|
| 32 |
+
self.assertRaises(AssertionError, pytree.Base)
|
| 33 |
+
|
| 34 |
+
def test_leaf(self):
|
| 35 |
+
l1 = pytree.Leaf(100, "foo")
|
| 36 |
+
self.assertEqual(l1.type, 100)
|
| 37 |
+
self.assertEqual(l1.value, "foo")
|
| 38 |
+
|
| 39 |
+
def test_leaf_repr(self):
|
| 40 |
+
l1 = pytree.Leaf(100, "foo")
|
| 41 |
+
self.assertEqual(repr(l1), "Leaf(100, 'foo')")
|
| 42 |
+
|
| 43 |
+
def test_leaf_str(self):
|
| 44 |
+
l1 = pytree.Leaf(100, "foo")
|
| 45 |
+
self.assertEqual(str(l1), "foo")
|
| 46 |
+
l2 = pytree.Leaf(100, "foo", context=(" ", (10, 1)))
|
| 47 |
+
self.assertEqual(str(l2), " foo")
|
| 48 |
+
|
| 49 |
+
def test_leaf_str_numeric_value(self):
|
| 50 |
+
# Make sure that the Leaf's value is stringified. Failing to
|
| 51 |
+
# do this can cause a TypeError in certain situations.
|
| 52 |
+
l1 = pytree.Leaf(2, 5)
|
| 53 |
+
l1.prefix = "foo_"
|
| 54 |
+
self.assertEqual(str(l1), "foo_5")
|
| 55 |
+
|
| 56 |
+
def test_leaf_equality(self):
|
| 57 |
+
l1 = pytree.Leaf(100, "foo")
|
| 58 |
+
l2 = pytree.Leaf(100, "foo", context=(" ", (1, 0)))
|
| 59 |
+
self.assertEqual(l1, l2)
|
| 60 |
+
l3 = pytree.Leaf(101, "foo")
|
| 61 |
+
l4 = pytree.Leaf(100, "bar")
|
| 62 |
+
self.assertNotEqual(l1, l3)
|
| 63 |
+
self.assertNotEqual(l1, l4)
|
| 64 |
+
|
| 65 |
+
def test_leaf_prefix(self):
|
| 66 |
+
l1 = pytree.Leaf(100, "foo")
|
| 67 |
+
self.assertEqual(l1.prefix, "")
|
| 68 |
+
self.assertFalse(l1.was_changed)
|
| 69 |
+
l1.prefix = " ##\n\n"
|
| 70 |
+
self.assertEqual(l1.prefix, " ##\n\n")
|
| 71 |
+
self.assertTrue(l1.was_changed)
|
| 72 |
+
|
| 73 |
+
def test_node(self):
|
| 74 |
+
l1 = pytree.Leaf(100, "foo")
|
| 75 |
+
l2 = pytree.Leaf(200, "bar")
|
| 76 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 77 |
+
self.assertEqual(n1.type, 1000)
|
| 78 |
+
self.assertEqual(n1.children, [l1, l2])
|
| 79 |
+
|
| 80 |
+
def test_node_repr(self):
|
| 81 |
+
l1 = pytree.Leaf(100, "foo")
|
| 82 |
+
l2 = pytree.Leaf(100, "bar", context=(" ", (1, 0)))
|
| 83 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 84 |
+
self.assertEqual(repr(n1),
|
| 85 |
+
"Node(1000, [%s, %s])" % (repr(l1), repr(l2)))
|
| 86 |
+
|
| 87 |
+
def test_node_str(self):
|
| 88 |
+
l1 = pytree.Leaf(100, "foo")
|
| 89 |
+
l2 = pytree.Leaf(100, "bar", context=(" ", (1, 0)))
|
| 90 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 91 |
+
self.assertEqual(str(n1), "foo bar")
|
| 92 |
+
|
| 93 |
+
def test_node_prefix(self):
|
| 94 |
+
l1 = pytree.Leaf(100, "foo")
|
| 95 |
+
self.assertEqual(l1.prefix, "")
|
| 96 |
+
n1 = pytree.Node(1000, [l1])
|
| 97 |
+
self.assertEqual(n1.prefix, "")
|
| 98 |
+
n1.prefix = " "
|
| 99 |
+
self.assertEqual(n1.prefix, " ")
|
| 100 |
+
self.assertEqual(l1.prefix, " ")
|
| 101 |
+
|
| 102 |
+
def test_get_suffix(self):
|
| 103 |
+
l1 = pytree.Leaf(100, "foo", prefix="a")
|
| 104 |
+
l2 = pytree.Leaf(100, "bar", prefix="b")
|
| 105 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 106 |
+
|
| 107 |
+
self.assertEqual(l1.get_suffix(), l2.prefix)
|
| 108 |
+
self.assertEqual(l2.get_suffix(), "")
|
| 109 |
+
self.assertEqual(n1.get_suffix(), "")
|
| 110 |
+
|
| 111 |
+
l3 = pytree.Leaf(100, "bar", prefix="c")
|
| 112 |
+
n2 = pytree.Node(1000, [n1, l3])
|
| 113 |
+
|
| 114 |
+
self.assertEqual(n1.get_suffix(), l3.prefix)
|
| 115 |
+
self.assertEqual(l3.get_suffix(), "")
|
| 116 |
+
self.assertEqual(n2.get_suffix(), "")
|
| 117 |
+
|
| 118 |
+
def test_node_equality(self):
|
| 119 |
+
n1 = pytree.Node(1000, ())
|
| 120 |
+
n2 = pytree.Node(1000, [], context=(" ", (1, 0)))
|
| 121 |
+
self.assertEqual(n1, n2)
|
| 122 |
+
n3 = pytree.Node(1001, ())
|
| 123 |
+
self.assertNotEqual(n1, n3)
|
| 124 |
+
|
| 125 |
+
def test_node_recursive_equality(self):
|
| 126 |
+
l1 = pytree.Leaf(100, "foo")
|
| 127 |
+
l2 = pytree.Leaf(100, "foo")
|
| 128 |
+
n1 = pytree.Node(1000, [l1])
|
| 129 |
+
n2 = pytree.Node(1000, [l2])
|
| 130 |
+
self.assertEqual(n1, n2)
|
| 131 |
+
l3 = pytree.Leaf(100, "bar")
|
| 132 |
+
n3 = pytree.Node(1000, [l3])
|
| 133 |
+
self.assertNotEqual(n1, n3)
|
| 134 |
+
|
| 135 |
+
def test_replace(self):
|
| 136 |
+
l1 = pytree.Leaf(100, "foo")
|
| 137 |
+
l2 = pytree.Leaf(100, "+")
|
| 138 |
+
l3 = pytree.Leaf(100, "bar")
|
| 139 |
+
n1 = pytree.Node(1000, [l1, l2, l3])
|
| 140 |
+
self.assertEqual(n1.children, [l1, l2, l3])
|
| 141 |
+
self.assertIsInstance(n1.children, list)
|
| 142 |
+
self.assertFalse(n1.was_changed)
|
| 143 |
+
l2new = pytree.Leaf(100, "-")
|
| 144 |
+
l2.replace(l2new)
|
| 145 |
+
self.assertEqual(n1.children, [l1, l2new, l3])
|
| 146 |
+
self.assertIsInstance(n1.children, list)
|
| 147 |
+
self.assertTrue(n1.was_changed)
|
| 148 |
+
|
| 149 |
+
def test_replace_with_list(self):
|
| 150 |
+
l1 = pytree.Leaf(100, "foo")
|
| 151 |
+
l2 = pytree.Leaf(100, "+")
|
| 152 |
+
l3 = pytree.Leaf(100, "bar")
|
| 153 |
+
n1 = pytree.Node(1000, [l1, l2, l3])
|
| 154 |
+
|
| 155 |
+
l2.replace([pytree.Leaf(100, "*"), pytree.Leaf(100, "*")])
|
| 156 |
+
self.assertEqual(str(n1), "foo**bar")
|
| 157 |
+
self.assertIsInstance(n1.children, list)
|
| 158 |
+
|
| 159 |
+
def test_leaves(self):
|
| 160 |
+
l1 = pytree.Leaf(100, "foo")
|
| 161 |
+
l2 = pytree.Leaf(100, "bar")
|
| 162 |
+
l3 = pytree.Leaf(100, "fooey")
|
| 163 |
+
n2 = pytree.Node(1000, [l1, l2])
|
| 164 |
+
n3 = pytree.Node(1000, [l3])
|
| 165 |
+
n1 = pytree.Node(1000, [n2, n3])
|
| 166 |
+
|
| 167 |
+
self.assertEqual(list(n1.leaves()), [l1, l2, l3])
|
| 168 |
+
|
| 169 |
+
def test_depth(self):
|
| 170 |
+
l1 = pytree.Leaf(100, "foo")
|
| 171 |
+
l2 = pytree.Leaf(100, "bar")
|
| 172 |
+
n2 = pytree.Node(1000, [l1, l2])
|
| 173 |
+
n3 = pytree.Node(1000, [])
|
| 174 |
+
n1 = pytree.Node(1000, [n2, n3])
|
| 175 |
+
|
| 176 |
+
self.assertEqual(l1.depth(), 2)
|
| 177 |
+
self.assertEqual(n3.depth(), 1)
|
| 178 |
+
self.assertEqual(n1.depth(), 0)
|
| 179 |
+
|
| 180 |
+
def test_post_order(self):
|
| 181 |
+
l1 = pytree.Leaf(100, "foo")
|
| 182 |
+
l2 = pytree.Leaf(100, "bar")
|
| 183 |
+
l3 = pytree.Leaf(100, "fooey")
|
| 184 |
+
c1 = pytree.Node(1000, [l1, l2])
|
| 185 |
+
n1 = pytree.Node(1000, [c1, l3])
|
| 186 |
+
self.assertEqual(list(n1.post_order()), [l1, l2, c1, l3, n1])
|
| 187 |
+
|
| 188 |
+
def test_pre_order(self):
|
| 189 |
+
l1 = pytree.Leaf(100, "foo")
|
| 190 |
+
l2 = pytree.Leaf(100, "bar")
|
| 191 |
+
l3 = pytree.Leaf(100, "fooey")
|
| 192 |
+
c1 = pytree.Node(1000, [l1, l2])
|
| 193 |
+
n1 = pytree.Node(1000, [c1, l3])
|
| 194 |
+
self.assertEqual(list(n1.pre_order()), [n1, c1, l1, l2, l3])
|
| 195 |
+
|
| 196 |
+
def test_changed(self):
|
| 197 |
+
l1 = pytree.Leaf(100, "f")
|
| 198 |
+
self.assertFalse(l1.was_changed)
|
| 199 |
+
l1.changed()
|
| 200 |
+
self.assertTrue(l1.was_changed)
|
| 201 |
+
|
| 202 |
+
l1 = pytree.Leaf(100, "f")
|
| 203 |
+
n1 = pytree.Node(1000, [l1])
|
| 204 |
+
self.assertFalse(n1.was_changed)
|
| 205 |
+
n1.changed()
|
| 206 |
+
self.assertTrue(n1.was_changed)
|
| 207 |
+
|
| 208 |
+
l1 = pytree.Leaf(100, "foo")
|
| 209 |
+
l2 = pytree.Leaf(100, "+")
|
| 210 |
+
l3 = pytree.Leaf(100, "bar")
|
| 211 |
+
n1 = pytree.Node(1000, [l1, l2, l3])
|
| 212 |
+
n2 = pytree.Node(1000, [n1])
|
| 213 |
+
self.assertFalse(l1.was_changed)
|
| 214 |
+
self.assertFalse(n1.was_changed)
|
| 215 |
+
self.assertFalse(n2.was_changed)
|
| 216 |
+
|
| 217 |
+
n1.changed()
|
| 218 |
+
self.assertTrue(n1.was_changed)
|
| 219 |
+
self.assertTrue(n2.was_changed)
|
| 220 |
+
self.assertFalse(l1.was_changed)
|
| 221 |
+
|
| 222 |
+
def test_leaf_constructor_prefix(self):
|
| 223 |
+
for prefix in ("xyz_", ""):
|
| 224 |
+
l1 = pytree.Leaf(100, "self", prefix=prefix)
|
| 225 |
+
self.assertTrue(str(l1), prefix + "self")
|
| 226 |
+
self.assertEqual(l1.prefix, prefix)
|
| 227 |
+
|
| 228 |
+
def test_node_constructor_prefix(self):
|
| 229 |
+
for prefix in ("xyz_", ""):
|
| 230 |
+
l1 = pytree.Leaf(100, "self")
|
| 231 |
+
l2 = pytree.Leaf(100, "foo", prefix="_")
|
| 232 |
+
n1 = pytree.Node(1000, [l1, l2], prefix=prefix)
|
| 233 |
+
self.assertTrue(str(n1), prefix + "self_foo")
|
| 234 |
+
self.assertEqual(n1.prefix, prefix)
|
| 235 |
+
self.assertEqual(l1.prefix, prefix)
|
| 236 |
+
self.assertEqual(l2.prefix, "_")
|
| 237 |
+
|
| 238 |
+
def test_remove(self):
|
| 239 |
+
l1 = pytree.Leaf(100, "foo")
|
| 240 |
+
l2 = pytree.Leaf(100, "foo")
|
| 241 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 242 |
+
n2 = pytree.Node(1000, [n1])
|
| 243 |
+
|
| 244 |
+
self.assertEqual(n1.remove(), 0)
|
| 245 |
+
self.assertEqual(n2.children, [])
|
| 246 |
+
self.assertEqual(l1.parent, n1)
|
| 247 |
+
self.assertEqual(n1.parent, None)
|
| 248 |
+
self.assertEqual(n2.parent, None)
|
| 249 |
+
self.assertFalse(n1.was_changed)
|
| 250 |
+
self.assertTrue(n2.was_changed)
|
| 251 |
+
|
| 252 |
+
self.assertEqual(l2.remove(), 1)
|
| 253 |
+
self.assertEqual(l1.remove(), 0)
|
| 254 |
+
self.assertEqual(n1.children, [])
|
| 255 |
+
self.assertEqual(l1.parent, None)
|
| 256 |
+
self.assertEqual(n1.parent, None)
|
| 257 |
+
self.assertEqual(n2.parent, None)
|
| 258 |
+
self.assertTrue(n1.was_changed)
|
| 259 |
+
self.assertTrue(n2.was_changed)
|
| 260 |
+
|
| 261 |
+
def test_remove_parentless(self):
|
| 262 |
+
n1 = pytree.Node(1000, [])
|
| 263 |
+
n1.remove()
|
| 264 |
+
self.assertEqual(n1.parent, None)
|
| 265 |
+
|
| 266 |
+
l1 = pytree.Leaf(100, "foo")
|
| 267 |
+
l1.remove()
|
| 268 |
+
self.assertEqual(l1.parent, None)
|
| 269 |
+
|
| 270 |
+
def test_node_set_child(self):
|
| 271 |
+
l1 = pytree.Leaf(100, "foo")
|
| 272 |
+
n1 = pytree.Node(1000, [l1])
|
| 273 |
+
|
| 274 |
+
l2 = pytree.Leaf(100, "bar")
|
| 275 |
+
n1.set_child(0, l2)
|
| 276 |
+
self.assertEqual(l1.parent, None)
|
| 277 |
+
self.assertEqual(l2.parent, n1)
|
| 278 |
+
self.assertEqual(n1.children, [l2])
|
| 279 |
+
|
| 280 |
+
n2 = pytree.Node(1000, [l1])
|
| 281 |
+
n2.set_child(0, n1)
|
| 282 |
+
self.assertEqual(l1.parent, None)
|
| 283 |
+
self.assertEqual(n1.parent, n2)
|
| 284 |
+
self.assertEqual(n2.parent, None)
|
| 285 |
+
self.assertEqual(n2.children, [n1])
|
| 286 |
+
|
| 287 |
+
self.assertRaises(IndexError, n1.set_child, 4, l2)
|
| 288 |
+
# I don't care what it raises, so long as it's an exception
|
| 289 |
+
self.assertRaises(Exception, n1.set_child, 0, list)
|
| 290 |
+
|
| 291 |
+
def test_node_insert_child(self):
|
| 292 |
+
l1 = pytree.Leaf(100, "foo")
|
| 293 |
+
n1 = pytree.Node(1000, [l1])
|
| 294 |
+
|
| 295 |
+
l2 = pytree.Leaf(100, "bar")
|
| 296 |
+
n1.insert_child(0, l2)
|
| 297 |
+
self.assertEqual(l2.parent, n1)
|
| 298 |
+
self.assertEqual(n1.children, [l2, l1])
|
| 299 |
+
|
| 300 |
+
l3 = pytree.Leaf(100, "abc")
|
| 301 |
+
n1.insert_child(2, l3)
|
| 302 |
+
self.assertEqual(n1.children, [l2, l1, l3])
|
| 303 |
+
|
| 304 |
+
# I don't care what it raises, so long as it's an exception
|
| 305 |
+
self.assertRaises(Exception, n1.insert_child, 0, list)
|
| 306 |
+
|
| 307 |
+
def test_node_append_child(self):
|
| 308 |
+
n1 = pytree.Node(1000, [])
|
| 309 |
+
|
| 310 |
+
l1 = pytree.Leaf(100, "foo")
|
| 311 |
+
n1.append_child(l1)
|
| 312 |
+
self.assertEqual(l1.parent, n1)
|
| 313 |
+
self.assertEqual(n1.children, [l1])
|
| 314 |
+
|
| 315 |
+
l2 = pytree.Leaf(100, "bar")
|
| 316 |
+
n1.append_child(l2)
|
| 317 |
+
self.assertEqual(l2.parent, n1)
|
| 318 |
+
self.assertEqual(n1.children, [l1, l2])
|
| 319 |
+
|
| 320 |
+
# I don't care what it raises, so long as it's an exception
|
| 321 |
+
self.assertRaises(Exception, n1.append_child, list)
|
| 322 |
+
|
| 323 |
+
def test_node_next_sibling(self):
|
| 324 |
+
n1 = pytree.Node(1000, [])
|
| 325 |
+
n2 = pytree.Node(1000, [])
|
| 326 |
+
p1 = pytree.Node(1000, [n1, n2])
|
| 327 |
+
|
| 328 |
+
self.assertIs(n1.next_sibling, n2)
|
| 329 |
+
self.assertEqual(n2.next_sibling, None)
|
| 330 |
+
self.assertEqual(p1.next_sibling, None)
|
| 331 |
+
|
| 332 |
+
def test_leaf_next_sibling(self):
|
| 333 |
+
l1 = pytree.Leaf(100, "a")
|
| 334 |
+
l2 = pytree.Leaf(100, "b")
|
| 335 |
+
p1 = pytree.Node(1000, [l1, l2])
|
| 336 |
+
|
| 337 |
+
self.assertIs(l1.next_sibling, l2)
|
| 338 |
+
self.assertEqual(l2.next_sibling, None)
|
| 339 |
+
self.assertEqual(p1.next_sibling, None)
|
| 340 |
+
|
| 341 |
+
def test_node_prev_sibling(self):
|
| 342 |
+
n1 = pytree.Node(1000, [])
|
| 343 |
+
n2 = pytree.Node(1000, [])
|
| 344 |
+
p1 = pytree.Node(1000, [n1, n2])
|
| 345 |
+
|
| 346 |
+
self.assertIs(n2.prev_sibling, n1)
|
| 347 |
+
self.assertEqual(n1.prev_sibling, None)
|
| 348 |
+
self.assertEqual(p1.prev_sibling, None)
|
| 349 |
+
|
| 350 |
+
def test_leaf_prev_sibling(self):
|
| 351 |
+
l1 = pytree.Leaf(100, "a")
|
| 352 |
+
l2 = pytree.Leaf(100, "b")
|
| 353 |
+
p1 = pytree.Node(1000, [l1, l2])
|
| 354 |
+
|
| 355 |
+
self.assertIs(l2.prev_sibling, l1)
|
| 356 |
+
self.assertEqual(l1.prev_sibling, None)
|
| 357 |
+
self.assertEqual(p1.prev_sibling, None)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class TestPatterns(support.TestCase):
|
| 361 |
+
|
| 362 |
+
"""Unit tests for tree matching patterns."""
|
| 363 |
+
|
| 364 |
+
def test_basic_patterns(self):
|
| 365 |
+
# Build a tree
|
| 366 |
+
l1 = pytree.Leaf(100, "foo")
|
| 367 |
+
l2 = pytree.Leaf(100, "bar")
|
| 368 |
+
l3 = pytree.Leaf(100, "foo")
|
| 369 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 370 |
+
n2 = pytree.Node(1000, [l3])
|
| 371 |
+
root = pytree.Node(1000, [n1, n2])
|
| 372 |
+
# Build a pattern matching a leaf
|
| 373 |
+
pl = pytree.LeafPattern(100, "foo", name="pl")
|
| 374 |
+
r = {}
|
| 375 |
+
self.assertFalse(pl.match(root, results=r))
|
| 376 |
+
self.assertEqual(r, {})
|
| 377 |
+
self.assertFalse(pl.match(n1, results=r))
|
| 378 |
+
self.assertEqual(r, {})
|
| 379 |
+
self.assertFalse(pl.match(n2, results=r))
|
| 380 |
+
self.assertEqual(r, {})
|
| 381 |
+
self.assertTrue(pl.match(l1, results=r))
|
| 382 |
+
self.assertEqual(r, {"pl": l1})
|
| 383 |
+
r = {}
|
| 384 |
+
self.assertFalse(pl.match(l2, results=r))
|
| 385 |
+
self.assertEqual(r, {})
|
| 386 |
+
# Build a pattern matching a node
|
| 387 |
+
pn = pytree.NodePattern(1000, [pl], name="pn")
|
| 388 |
+
self.assertFalse(pn.match(root, results=r))
|
| 389 |
+
self.assertEqual(r, {})
|
| 390 |
+
self.assertFalse(pn.match(n1, results=r))
|
| 391 |
+
self.assertEqual(r, {})
|
| 392 |
+
self.assertTrue(pn.match(n2, results=r))
|
| 393 |
+
self.assertEqual(r, {"pn": n2, "pl": l3})
|
| 394 |
+
r = {}
|
| 395 |
+
self.assertFalse(pn.match(l1, results=r))
|
| 396 |
+
self.assertEqual(r, {})
|
| 397 |
+
self.assertFalse(pn.match(l2, results=r))
|
| 398 |
+
self.assertEqual(r, {})
|
| 399 |
+
|
| 400 |
+
def test_wildcard(self):
|
| 401 |
+
# Build a tree for testing
|
| 402 |
+
l1 = pytree.Leaf(100, "foo")
|
| 403 |
+
l2 = pytree.Leaf(100, "bar")
|
| 404 |
+
l3 = pytree.Leaf(100, "foo")
|
| 405 |
+
n1 = pytree.Node(1000, [l1, l2])
|
| 406 |
+
n2 = pytree.Node(1000, [l3])
|
| 407 |
+
root = pytree.Node(1000, [n1, n2])
|
| 408 |
+
# Build a pattern
|
| 409 |
+
pl = pytree.LeafPattern(100, "foo", name="pl")
|
| 410 |
+
pn = pytree.NodePattern(1000, [pl], name="pn")
|
| 411 |
+
pw = pytree.WildcardPattern([[pn], [pl, pl]], name="pw")
|
| 412 |
+
r = {}
|
| 413 |
+
self.assertFalse(pw.match_seq([root], r))
|
| 414 |
+
self.assertEqual(r, {})
|
| 415 |
+
self.assertFalse(pw.match_seq([n1], r))
|
| 416 |
+
self.assertEqual(r, {})
|
| 417 |
+
self.assertTrue(pw.match_seq([n2], r))
|
| 418 |
+
# These are easier to debug
|
| 419 |
+
self.assertEqual(sorted(r.keys()), ["pl", "pn", "pw"])
|
| 420 |
+
self.assertEqual(r["pl"], l1)
|
| 421 |
+
self.assertEqual(r["pn"], n2)
|
| 422 |
+
self.assertEqual(r["pw"], [n2])
|
| 423 |
+
# But this is equivalent
|
| 424 |
+
self.assertEqual(r, {"pl": l1, "pn": n2, "pw": [n2]})
|
| 425 |
+
r = {}
|
| 426 |
+
self.assertTrue(pw.match_seq([l1, l3], r))
|
| 427 |
+
self.assertEqual(r, {"pl": l3, "pw": [l1, l3]})
|
| 428 |
+
self.assertIs(r["pl"], l3)
|
| 429 |
+
r = {}
|
| 430 |
+
|
| 431 |
+
def test_generate_matches(self):
|
| 432 |
+
la = pytree.Leaf(1, "a")
|
| 433 |
+
lb = pytree.Leaf(1, "b")
|
| 434 |
+
lc = pytree.Leaf(1, "c")
|
| 435 |
+
ld = pytree.Leaf(1, "d")
|
| 436 |
+
le = pytree.Leaf(1, "e")
|
| 437 |
+
lf = pytree.Leaf(1, "f")
|
| 438 |
+
leaves = [la, lb, lc, ld, le, lf]
|
| 439 |
+
root = pytree.Node(1000, leaves)
|
| 440 |
+
pa = pytree.LeafPattern(1, "a", "pa")
|
| 441 |
+
pb = pytree.LeafPattern(1, "b", "pb")
|
| 442 |
+
pc = pytree.LeafPattern(1, "c", "pc")
|
| 443 |
+
pd = pytree.LeafPattern(1, "d", "pd")
|
| 444 |
+
pe = pytree.LeafPattern(1, "e", "pe")
|
| 445 |
+
pf = pytree.LeafPattern(1, "f", "pf")
|
| 446 |
+
pw = pytree.WildcardPattern([[pa, pb, pc], [pd, pe],
|
| 447 |
+
[pa, pb], [pc, pd], [pe, pf]],
|
| 448 |
+
min=1, max=4, name="pw")
|
| 449 |
+
self.assertEqual([x[0] for x in pw.generate_matches(leaves)],
|
| 450 |
+
[3, 5, 2, 4, 6])
|
| 451 |
+
pr = pytree.NodePattern(type=1000, content=[pw], name="pr")
|
| 452 |
+
matches = list(pytree.generate_matches([pr], [root]))
|
| 453 |
+
self.assertEqual(len(matches), 1)
|
| 454 |
+
c, r = matches[0]
|
| 455 |
+
self.assertEqual(c, 1)
|
| 456 |
+
self.assertEqual(str(r["pr"]), "abcdef")
|
| 457 |
+
self.assertEqual(r["pw"], [la, lb, lc, ld, le, lf])
|
| 458 |
+
for c in "abcdef":
|
| 459 |
+
self.assertEqual(r["p" + c], pytree.Leaf(1, c))
|
| 460 |
+
|
| 461 |
+
def test_has_key_example(self):
|
| 462 |
+
pattern = pytree.NodePattern(331,
|
| 463 |
+
(pytree.LeafPattern(7),
|
| 464 |
+
pytree.WildcardPattern(name="args"),
|
| 465 |
+
pytree.LeafPattern(8)))
|
| 466 |
+
l1 = pytree.Leaf(7, "(")
|
| 467 |
+
l2 = pytree.Leaf(3, "x")
|
| 468 |
+
l3 = pytree.Leaf(8, ")")
|
| 469 |
+
node = pytree.Node(331, [l1, l2, l3])
|
| 470 |
+
r = {}
|
| 471 |
+
self.assertTrue(pattern.match(node, r))
|
| 472 |
+
self.assertEqual(r["args"], [l2])
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_refactor.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit tests for refactor.py.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
import os
|
| 7 |
+
import codecs
|
| 8 |
+
import io
|
| 9 |
+
import re
|
| 10 |
+
import tempfile
|
| 11 |
+
import shutil
|
| 12 |
+
import unittest
|
| 13 |
+
|
| 14 |
+
from lib2to3 import refactor, pygram, fixer_base
|
| 15 |
+
from lib2to3.pgen2 import token
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
|
| 19 |
+
FIXER_DIR = os.path.join(TEST_DATA_DIR, "fixers")
|
| 20 |
+
|
| 21 |
+
sys.path.append(FIXER_DIR)
|
| 22 |
+
try:
|
| 23 |
+
_DEFAULT_FIXERS = refactor.get_fixers_from_package("myfixes")
|
| 24 |
+
finally:
|
| 25 |
+
sys.path.pop()
|
| 26 |
+
|
| 27 |
+
_2TO3_FIXERS = refactor.get_fixers_from_package("lib2to3.fixes")
|
| 28 |
+
|
| 29 |
+
class TestRefactoringTool(unittest.TestCase):
|
| 30 |
+
|
| 31 |
+
def setUp(self):
|
| 32 |
+
sys.path.append(FIXER_DIR)
|
| 33 |
+
|
| 34 |
+
def tearDown(self):
|
| 35 |
+
sys.path.pop()
|
| 36 |
+
|
| 37 |
+
def check_instances(self, instances, classes):
|
| 38 |
+
for inst, cls in zip(instances, classes):
|
| 39 |
+
if not isinstance(inst, cls):
|
| 40 |
+
self.fail("%s are not instances of %s" % instances, classes)
|
| 41 |
+
|
| 42 |
+
def rt(self, options=None, fixers=_DEFAULT_FIXERS, explicit=None):
|
| 43 |
+
return refactor.RefactoringTool(fixers, options, explicit)
|
| 44 |
+
|
| 45 |
+
def test_print_function_option(self):
|
| 46 |
+
rt = self.rt({"print_function" : True})
|
| 47 |
+
self.assertNotIn("print", rt.grammar.keywords)
|
| 48 |
+
self.assertNotIn("print", rt.driver.grammar.keywords)
|
| 49 |
+
|
| 50 |
+
def test_exec_function_option(self):
|
| 51 |
+
rt = self.rt({"exec_function" : True})
|
| 52 |
+
self.assertNotIn("exec", rt.grammar.keywords)
|
| 53 |
+
self.assertNotIn("exec", rt.driver.grammar.keywords)
|
| 54 |
+
|
| 55 |
+
def test_write_unchanged_files_option(self):
|
| 56 |
+
rt = self.rt()
|
| 57 |
+
self.assertFalse(rt.write_unchanged_files)
|
| 58 |
+
rt = self.rt({"write_unchanged_files" : True})
|
| 59 |
+
self.assertTrue(rt.write_unchanged_files)
|
| 60 |
+
|
| 61 |
+
def test_fixer_loading_helpers(self):
|
| 62 |
+
contents = ["explicit", "first", "last", "parrot", "preorder"]
|
| 63 |
+
non_prefixed = refactor.get_all_fix_names("myfixes")
|
| 64 |
+
prefixed = refactor.get_all_fix_names("myfixes", False)
|
| 65 |
+
full_names = refactor.get_fixers_from_package("myfixes")
|
| 66 |
+
self.assertEqual(prefixed, ["fix_" + name for name in contents])
|
| 67 |
+
self.assertEqual(non_prefixed, contents)
|
| 68 |
+
self.assertEqual(full_names,
|
| 69 |
+
["myfixes.fix_" + name for name in contents])
|
| 70 |
+
|
| 71 |
+
def test_detect_future_features(self):
|
| 72 |
+
run = refactor._detect_future_features
|
| 73 |
+
fs = frozenset
|
| 74 |
+
empty = fs()
|
| 75 |
+
self.assertEqual(run(""), empty)
|
| 76 |
+
self.assertEqual(run("from __future__ import print_function"),
|
| 77 |
+
fs(("print_function",)))
|
| 78 |
+
self.assertEqual(run("from __future__ import generators"),
|
| 79 |
+
fs(("generators",)))
|
| 80 |
+
self.assertEqual(run("from __future__ import generators, feature"),
|
| 81 |
+
fs(("generators", "feature")))
|
| 82 |
+
inp = "from __future__ import generators, print_function"
|
| 83 |
+
self.assertEqual(run(inp), fs(("generators", "print_function")))
|
| 84 |
+
inp ="from __future__ import print_function, generators"
|
| 85 |
+
self.assertEqual(run(inp), fs(("print_function", "generators")))
|
| 86 |
+
inp = "from __future__ import (print_function,)"
|
| 87 |
+
self.assertEqual(run(inp), fs(("print_function",)))
|
| 88 |
+
inp = "from __future__ import (generators, print_function)"
|
| 89 |
+
self.assertEqual(run(inp), fs(("generators", "print_function")))
|
| 90 |
+
inp = "from __future__ import (generators, nested_scopes)"
|
| 91 |
+
self.assertEqual(run(inp), fs(("generators", "nested_scopes")))
|
| 92 |
+
inp = """from __future__ import generators
|
| 93 |
+
from __future__ import print_function"""
|
| 94 |
+
self.assertEqual(run(inp), fs(("generators", "print_function")))
|
| 95 |
+
invalid = ("from",
|
| 96 |
+
"from 4",
|
| 97 |
+
"from x",
|
| 98 |
+
"from x 5",
|
| 99 |
+
"from x im",
|
| 100 |
+
"from x import",
|
| 101 |
+
"from x import 4",
|
| 102 |
+
)
|
| 103 |
+
for inp in invalid:
|
| 104 |
+
self.assertEqual(run(inp), empty)
|
| 105 |
+
inp = "'docstring'\nfrom __future__ import print_function"
|
| 106 |
+
self.assertEqual(run(inp), fs(("print_function",)))
|
| 107 |
+
inp = "'docstring'\n'somng'\nfrom __future__ import print_function"
|
| 108 |
+
self.assertEqual(run(inp), empty)
|
| 109 |
+
inp = "# comment\nfrom __future__ import print_function"
|
| 110 |
+
self.assertEqual(run(inp), fs(("print_function",)))
|
| 111 |
+
inp = "# comment\n'doc'\nfrom __future__ import print_function"
|
| 112 |
+
self.assertEqual(run(inp), fs(("print_function",)))
|
| 113 |
+
inp = "class x: pass\nfrom __future__ import print_function"
|
| 114 |
+
self.assertEqual(run(inp), empty)
|
| 115 |
+
|
| 116 |
+
def test_get_headnode_dict(self):
|
| 117 |
+
class NoneFix(fixer_base.BaseFix):
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
class FileInputFix(fixer_base.BaseFix):
|
| 121 |
+
PATTERN = "file_input< any * >"
|
| 122 |
+
|
| 123 |
+
class SimpleFix(fixer_base.BaseFix):
|
| 124 |
+
PATTERN = "'name'"
|
| 125 |
+
|
| 126 |
+
no_head = NoneFix({}, [])
|
| 127 |
+
with_head = FileInputFix({}, [])
|
| 128 |
+
simple = SimpleFix({}, [])
|
| 129 |
+
d = refactor._get_headnode_dict([no_head, with_head, simple])
|
| 130 |
+
top_fixes = d.pop(pygram.python_symbols.file_input)
|
| 131 |
+
self.assertEqual(top_fixes, [with_head, no_head])
|
| 132 |
+
name_fixes = d.pop(token.NAME)
|
| 133 |
+
self.assertEqual(name_fixes, [simple, no_head])
|
| 134 |
+
for fixes in d.values():
|
| 135 |
+
self.assertEqual(fixes, [no_head])
|
| 136 |
+
|
| 137 |
+
def test_fixer_loading(self):
|
| 138 |
+
from myfixes.fix_first import FixFirst
|
| 139 |
+
from myfixes.fix_last import FixLast
|
| 140 |
+
from myfixes.fix_parrot import FixParrot
|
| 141 |
+
from myfixes.fix_preorder import FixPreorder
|
| 142 |
+
|
| 143 |
+
rt = self.rt()
|
| 144 |
+
pre, post = rt.get_fixers()
|
| 145 |
+
|
| 146 |
+
self.check_instances(pre, [FixPreorder])
|
| 147 |
+
self.check_instances(post, [FixFirst, FixParrot, FixLast])
|
| 148 |
+
|
| 149 |
+
def test_naughty_fixers(self):
|
| 150 |
+
self.assertRaises(ImportError, self.rt, fixers=["not_here"])
|
| 151 |
+
self.assertRaises(refactor.FixerError, self.rt, fixers=["no_fixer_cls"])
|
| 152 |
+
self.assertRaises(refactor.FixerError, self.rt, fixers=["bad_order"])
|
| 153 |
+
|
| 154 |
+
def test_refactor_string(self):
|
| 155 |
+
rt = self.rt()
|
| 156 |
+
input = "def parrot(): pass\n\n"
|
| 157 |
+
tree = rt.refactor_string(input, "<test>")
|
| 158 |
+
self.assertNotEqual(str(tree), input)
|
| 159 |
+
|
| 160 |
+
input = "def f(): pass\n\n"
|
| 161 |
+
tree = rt.refactor_string(input, "<test>")
|
| 162 |
+
self.assertEqual(str(tree), input)
|
| 163 |
+
|
| 164 |
+
def test_refactor_stdin(self):
|
| 165 |
+
|
| 166 |
+
class MyRT(refactor.RefactoringTool):
|
| 167 |
+
|
| 168 |
+
def print_output(self, old_text, new_text, filename, equal):
|
| 169 |
+
results.extend([old_text, new_text, filename, equal])
|
| 170 |
+
|
| 171 |
+
results = []
|
| 172 |
+
rt = MyRT(_DEFAULT_FIXERS)
|
| 173 |
+
save = sys.stdin
|
| 174 |
+
sys.stdin = io.StringIO("def parrot(): pass\n\n")
|
| 175 |
+
try:
|
| 176 |
+
rt.refactor_stdin()
|
| 177 |
+
finally:
|
| 178 |
+
sys.stdin = save
|
| 179 |
+
expected = ["def parrot(): pass\n\n",
|
| 180 |
+
"def cheese(): pass\n\n",
|
| 181 |
+
"<stdin>", False]
|
| 182 |
+
self.assertEqual(results, expected)
|
| 183 |
+
|
| 184 |
+
def check_file_refactoring(self, test_file, fixers=_2TO3_FIXERS,
|
| 185 |
+
options=None, mock_log_debug=None,
|
| 186 |
+
actually_write=True):
|
| 187 |
+
test_file = self.init_test_file(test_file)
|
| 188 |
+
old_contents = self.read_file(test_file)
|
| 189 |
+
rt = self.rt(fixers=fixers, options=options)
|
| 190 |
+
if mock_log_debug:
|
| 191 |
+
rt.log_debug = mock_log_debug
|
| 192 |
+
|
| 193 |
+
rt.refactor_file(test_file)
|
| 194 |
+
self.assertEqual(old_contents, self.read_file(test_file))
|
| 195 |
+
|
| 196 |
+
if not actually_write:
|
| 197 |
+
return
|
| 198 |
+
rt.refactor_file(test_file, True)
|
| 199 |
+
new_contents = self.read_file(test_file)
|
| 200 |
+
self.assertNotEqual(old_contents, new_contents)
|
| 201 |
+
return new_contents
|
| 202 |
+
|
| 203 |
+
def init_test_file(self, test_file):
|
| 204 |
+
tmpdir = tempfile.mkdtemp(prefix="2to3-test_refactor")
|
| 205 |
+
self.addCleanup(shutil.rmtree, tmpdir)
|
| 206 |
+
shutil.copy(test_file, tmpdir)
|
| 207 |
+
test_file = os.path.join(tmpdir, os.path.basename(test_file))
|
| 208 |
+
os.chmod(test_file, 0o644)
|
| 209 |
+
return test_file
|
| 210 |
+
|
| 211 |
+
def read_file(self, test_file):
|
| 212 |
+
with open(test_file, "rb") as fp:
|
| 213 |
+
return fp.read()
|
| 214 |
+
|
| 215 |
+
def refactor_file(self, test_file, fixers=_2TO3_FIXERS):
|
| 216 |
+
test_file = self.init_test_file(test_file)
|
| 217 |
+
old_contents = self.read_file(test_file)
|
| 218 |
+
rt = self.rt(fixers=fixers)
|
| 219 |
+
rt.refactor_file(test_file, True)
|
| 220 |
+
new_contents = self.read_file(test_file)
|
| 221 |
+
return old_contents, new_contents
|
| 222 |
+
|
| 223 |
+
def test_refactor_file(self):
|
| 224 |
+
test_file = os.path.join(FIXER_DIR, "parrot_example.py")
|
| 225 |
+
self.check_file_refactoring(test_file, _DEFAULT_FIXERS)
|
| 226 |
+
|
| 227 |
+
def test_refactor_file_write_unchanged_file(self):
|
| 228 |
+
test_file = os.path.join(FIXER_DIR, "parrot_example.py")
|
| 229 |
+
debug_messages = []
|
| 230 |
+
def recording_log_debug(msg, *args):
|
| 231 |
+
debug_messages.append(msg % args)
|
| 232 |
+
self.check_file_refactoring(test_file, fixers=(),
|
| 233 |
+
options={"write_unchanged_files": True},
|
| 234 |
+
mock_log_debug=recording_log_debug,
|
| 235 |
+
actually_write=False)
|
| 236 |
+
# Testing that it logged this message when write=False was passed is
|
| 237 |
+
# sufficient to see that it did not bail early after "No changes".
|
| 238 |
+
message_regex = r"Not writing changes to .*%s" % \
|
| 239 |
+
re.escape(os.sep + os.path.basename(test_file))
|
| 240 |
+
for message in debug_messages:
|
| 241 |
+
if "Not writing changes" in message:
|
| 242 |
+
self.assertRegex(message, message_regex)
|
| 243 |
+
break
|
| 244 |
+
else:
|
| 245 |
+
self.fail("%r not matched in %r" % (message_regex, debug_messages))
|
| 246 |
+
|
| 247 |
+
def test_refactor_dir(self):
|
| 248 |
+
def check(structure, expected):
|
| 249 |
+
def mock_refactor_file(self, f, *args):
|
| 250 |
+
got.append(f)
|
| 251 |
+
save_func = refactor.RefactoringTool.refactor_file
|
| 252 |
+
refactor.RefactoringTool.refactor_file = mock_refactor_file
|
| 253 |
+
rt = self.rt()
|
| 254 |
+
got = []
|
| 255 |
+
dir = tempfile.mkdtemp(prefix="2to3-test_refactor")
|
| 256 |
+
try:
|
| 257 |
+
os.mkdir(os.path.join(dir, "a_dir"))
|
| 258 |
+
for fn in structure:
|
| 259 |
+
open(os.path.join(dir, fn), "wb").close()
|
| 260 |
+
rt.refactor_dir(dir)
|
| 261 |
+
finally:
|
| 262 |
+
refactor.RefactoringTool.refactor_file = save_func
|
| 263 |
+
shutil.rmtree(dir)
|
| 264 |
+
self.assertEqual(got,
|
| 265 |
+
[os.path.join(dir, path) for path in expected])
|
| 266 |
+
check([], [])
|
| 267 |
+
tree = ["nothing",
|
| 268 |
+
"hi.py",
|
| 269 |
+
".dumb",
|
| 270 |
+
".after.py",
|
| 271 |
+
"notpy.npy",
|
| 272 |
+
"sappy"]
|
| 273 |
+
expected = ["hi.py"]
|
| 274 |
+
check(tree, expected)
|
| 275 |
+
tree = ["hi.py",
|
| 276 |
+
os.path.join("a_dir", "stuff.py")]
|
| 277 |
+
check(tree, tree)
|
| 278 |
+
|
| 279 |
+
def test_file_encoding(self):
|
| 280 |
+
fn = os.path.join(TEST_DATA_DIR, "different_encoding.py")
|
| 281 |
+
self.check_file_refactoring(fn)
|
| 282 |
+
|
| 283 |
+
def test_false_file_encoding(self):
|
| 284 |
+
fn = os.path.join(TEST_DATA_DIR, "false_encoding.py")
|
| 285 |
+
data = self.check_file_refactoring(fn)
|
| 286 |
+
|
| 287 |
+
def test_bom(self):
|
| 288 |
+
fn = os.path.join(TEST_DATA_DIR, "bom.py")
|
| 289 |
+
data = self.check_file_refactoring(fn)
|
| 290 |
+
self.assertTrue(data.startswith(codecs.BOM_UTF8))
|
| 291 |
+
|
| 292 |
+
def test_crlf_newlines(self):
|
| 293 |
+
old_sep = os.linesep
|
| 294 |
+
os.linesep = "\r\n"
|
| 295 |
+
try:
|
| 296 |
+
fn = os.path.join(TEST_DATA_DIR, "crlf.py")
|
| 297 |
+
fixes = refactor.get_fixers_from_package("lib2to3.fixes")
|
| 298 |
+
self.check_file_refactoring(fn, fixes)
|
| 299 |
+
finally:
|
| 300 |
+
os.linesep = old_sep
|
| 301 |
+
|
| 302 |
+
def test_crlf_unchanged(self):
|
| 303 |
+
fn = os.path.join(TEST_DATA_DIR, "crlf.py")
|
| 304 |
+
old, new = self.refactor_file(fn)
|
| 305 |
+
self.assertIn(b"\r\n", old)
|
| 306 |
+
self.assertIn(b"\r\n", new)
|
| 307 |
+
self.assertNotIn(b"\r\r\n", new)
|
| 308 |
+
|
| 309 |
+
def test_refactor_docstring(self):
|
| 310 |
+
rt = self.rt()
|
| 311 |
+
|
| 312 |
+
doc = """
|
| 313 |
+
>>> example()
|
| 314 |
+
42
|
| 315 |
+
"""
|
| 316 |
+
out = rt.refactor_docstring(doc, "<test>")
|
| 317 |
+
self.assertEqual(out, doc)
|
| 318 |
+
|
| 319 |
+
doc = """
|
| 320 |
+
>>> def parrot():
|
| 321 |
+
... return 43
|
| 322 |
+
"""
|
| 323 |
+
out = rt.refactor_docstring(doc, "<test>")
|
| 324 |
+
self.assertNotEqual(out, doc)
|
| 325 |
+
|
| 326 |
+
def test_explicit(self):
|
| 327 |
+
from myfixes.fix_explicit import FixExplicit
|
| 328 |
+
|
| 329 |
+
rt = self.rt(fixers=["myfixes.fix_explicit"])
|
| 330 |
+
self.assertEqual(len(rt.post_order), 0)
|
| 331 |
+
|
| 332 |
+
rt = self.rt(explicit=["myfixes.fix_explicit"])
|
| 333 |
+
for fix in rt.post_order:
|
| 334 |
+
if isinstance(fix, FixExplicit):
|
| 335 |
+
break
|
| 336 |
+
else:
|
| 337 |
+
self.fail("explicit fixer not loaded")
|
miniconda3/envs/ladir/lib/python3.10/lib2to3/tests/test_util.py
ADDED
|
@@ -0,0 +1,591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 8 |
+
from lib2to3 import fixer_util
|
| 9 |
+
from lib2to3.fixer_util import Attr, Name, Call, Comma
|
| 10 |
+
from lib2to3.pgen2 import token
|
| 11 |
+
|
| 12 |
+
def parse(code, strip_levels=0):
|
| 13 |
+
# The topmost node is file_input, which we don't care about.
|
| 14 |
+
# The next-topmost node is a *_stmt node, which we also don't care about
|
| 15 |
+
tree = support.parse_string(code)
|
| 16 |
+
for i in range(strip_levels):
|
| 17 |
+
tree = tree.children[0]
|
| 18 |
+
tree.parent = None
|
| 19 |
+
return tree
|
| 20 |
+
|
| 21 |
+
class MacroTestCase(support.TestCase):
|
| 22 |
+
def assertStr(self, node, string):
|
| 23 |
+
if isinstance(node, (tuple, list)):
|
| 24 |
+
node = Node(fixer_util.syms.simple_stmt, node)
|
| 25 |
+
self.assertEqual(str(node), string)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Test_is_tuple(support.TestCase):
|
| 29 |
+
def is_tuple(self, string):
|
| 30 |
+
return fixer_util.is_tuple(parse(string, strip_levels=2))
|
| 31 |
+
|
| 32 |
+
def test_valid(self):
|
| 33 |
+
self.assertTrue(self.is_tuple("(a, b)"))
|
| 34 |
+
self.assertTrue(self.is_tuple("(a, (b, c))"))
|
| 35 |
+
self.assertTrue(self.is_tuple("((a, (b, c)),)"))
|
| 36 |
+
self.assertTrue(self.is_tuple("(a,)"))
|
| 37 |
+
self.assertTrue(self.is_tuple("()"))
|
| 38 |
+
|
| 39 |
+
def test_invalid(self):
|
| 40 |
+
self.assertFalse(self.is_tuple("(a)"))
|
| 41 |
+
self.assertFalse(self.is_tuple("('foo') % (b, c)"))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Test_is_list(support.TestCase):
|
| 45 |
+
def is_list(self, string):
|
| 46 |
+
return fixer_util.is_list(parse(string, strip_levels=2))
|
| 47 |
+
|
| 48 |
+
def test_valid(self):
|
| 49 |
+
self.assertTrue(self.is_list("[]"))
|
| 50 |
+
self.assertTrue(self.is_list("[a]"))
|
| 51 |
+
self.assertTrue(self.is_list("[a, b]"))
|
| 52 |
+
self.assertTrue(self.is_list("[a, [b, c]]"))
|
| 53 |
+
self.assertTrue(self.is_list("[[a, [b, c]],]"))
|
| 54 |
+
|
| 55 |
+
def test_invalid(self):
|
| 56 |
+
self.assertFalse(self.is_list("[]+[]"))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Test_Attr(MacroTestCase):
|
| 60 |
+
def test(self):
|
| 61 |
+
call = parse("foo()", strip_levels=2)
|
| 62 |
+
|
| 63 |
+
self.assertStr(Attr(Name("a"), Name("b")), "a.b")
|
| 64 |
+
self.assertStr(Attr(call, Name("b")), "foo().b")
|
| 65 |
+
|
| 66 |
+
def test_returns(self):
|
| 67 |
+
attr = Attr(Name("a"), Name("b"))
|
| 68 |
+
self.assertEqual(type(attr), list)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class Test_Name(MacroTestCase):
|
| 72 |
+
def test(self):
|
| 73 |
+
self.assertStr(Name("a"), "a")
|
| 74 |
+
self.assertStr(Name("foo.foo().bar"), "foo.foo().bar")
|
| 75 |
+
self.assertStr(Name("a", prefix="b"), "ba")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Test_Call(MacroTestCase):
|
| 79 |
+
def _Call(self, name, args=None, prefix=None):
|
| 80 |
+
"""Help the next test"""
|
| 81 |
+
children = []
|
| 82 |
+
if isinstance(args, list):
|
| 83 |
+
for arg in args:
|
| 84 |
+
children.append(arg)
|
| 85 |
+
children.append(Comma())
|
| 86 |
+
children.pop()
|
| 87 |
+
return Call(Name(name), children, prefix)
|
| 88 |
+
|
| 89 |
+
def test(self):
|
| 90 |
+
kids = [None,
|
| 91 |
+
[Leaf(token.NUMBER, 1), Leaf(token.NUMBER, 2),
|
| 92 |
+
Leaf(token.NUMBER, 3)],
|
| 93 |
+
[Leaf(token.NUMBER, 1), Leaf(token.NUMBER, 3),
|
| 94 |
+
Leaf(token.NUMBER, 2), Leaf(token.NUMBER, 4)],
|
| 95 |
+
[Leaf(token.STRING, "b"), Leaf(token.STRING, "j", prefix=" ")]
|
| 96 |
+
]
|
| 97 |
+
self.assertStr(self._Call("A"), "A()")
|
| 98 |
+
self.assertStr(self._Call("b", kids[1]), "b(1,2,3)")
|
| 99 |
+
self.assertStr(self._Call("a.b().c", kids[2]), "a.b().c(1,3,2,4)")
|
| 100 |
+
self.assertStr(self._Call("d", kids[3], prefix=" "), " d(b, j)")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class Test_does_tree_import(support.TestCase):
|
| 104 |
+
def _find_bind_rec(self, name, node):
|
| 105 |
+
# Search a tree for a binding -- used to find the starting
|
| 106 |
+
# point for these tests.
|
| 107 |
+
c = fixer_util.find_binding(name, node)
|
| 108 |
+
if c: return c
|
| 109 |
+
for child in node.children:
|
| 110 |
+
c = self._find_bind_rec(name, child)
|
| 111 |
+
if c: return c
|
| 112 |
+
|
| 113 |
+
def does_tree_import(self, package, name, string):
|
| 114 |
+
node = parse(string)
|
| 115 |
+
# Find the binding of start -- that's what we'll go from
|
| 116 |
+
node = self._find_bind_rec('start', node)
|
| 117 |
+
return fixer_util.does_tree_import(package, name, node)
|
| 118 |
+
|
| 119 |
+
def try_with(self, string):
|
| 120 |
+
failing_tests = (("a", "a", "from a import b"),
|
| 121 |
+
("a.d", "a", "from a.d import b"),
|
| 122 |
+
("d.a", "a", "from d.a import b"),
|
| 123 |
+
(None, "a", "import b"),
|
| 124 |
+
(None, "a", "import b, c, d"))
|
| 125 |
+
for package, name, import_ in failing_tests:
|
| 126 |
+
n = self.does_tree_import(package, name, import_ + "\n" + string)
|
| 127 |
+
self.assertFalse(n)
|
| 128 |
+
n = self.does_tree_import(package, name, string + "\n" + import_)
|
| 129 |
+
self.assertFalse(n)
|
| 130 |
+
|
| 131 |
+
passing_tests = (("a", "a", "from a import a"),
|
| 132 |
+
("x", "a", "from x import a"),
|
| 133 |
+
("x", "a", "from x import b, c, a, d"),
|
| 134 |
+
("x.b", "a", "from x.b import a"),
|
| 135 |
+
("x.b", "a", "from x.b import b, c, a, d"),
|
| 136 |
+
(None, "a", "import a"),
|
| 137 |
+
(None, "a", "import b, c, a, d"))
|
| 138 |
+
for package, name, import_ in passing_tests:
|
| 139 |
+
n = self.does_tree_import(package, name, import_ + "\n" + string)
|
| 140 |
+
self.assertTrue(n)
|
| 141 |
+
n = self.does_tree_import(package, name, string + "\n" + import_)
|
| 142 |
+
self.assertTrue(n)
|
| 143 |
+
|
| 144 |
+
def test_in_function(self):
|
| 145 |
+
self.try_with("def foo():\n\tbar.baz()\n\tstart=3")
|
| 146 |
+
|
| 147 |
+
class Test_find_binding(support.TestCase):
|
| 148 |
+
def find_binding(self, name, string, package=None):
|
| 149 |
+
return fixer_util.find_binding(name, parse(string), package)
|
| 150 |
+
|
| 151 |
+
def test_simple_assignment(self):
|
| 152 |
+
self.assertTrue(self.find_binding("a", "a = b"))
|
| 153 |
+
self.assertTrue(self.find_binding("a", "a = [b, c, d]"))
|
| 154 |
+
self.assertTrue(self.find_binding("a", "a = foo()"))
|
| 155 |
+
self.assertTrue(self.find_binding("a", "a = foo().foo.foo[6][foo]"))
|
| 156 |
+
self.assertFalse(self.find_binding("a", "foo = a"))
|
| 157 |
+
self.assertFalse(self.find_binding("a", "foo = (a, b, c)"))
|
| 158 |
+
|
| 159 |
+
def test_tuple_assignment(self):
|
| 160 |
+
self.assertTrue(self.find_binding("a", "(a,) = b"))
|
| 161 |
+
self.assertTrue(self.find_binding("a", "(a, b, c) = [b, c, d]"))
|
| 162 |
+
self.assertTrue(self.find_binding("a", "(c, (d, a), b) = foo()"))
|
| 163 |
+
self.assertTrue(self.find_binding("a", "(a, b) = foo().foo[6][foo]"))
|
| 164 |
+
self.assertFalse(self.find_binding("a", "(foo, b) = (b, a)"))
|
| 165 |
+
self.assertFalse(self.find_binding("a", "(foo, (b, c)) = (a, b, c)"))
|
| 166 |
+
|
| 167 |
+
def test_list_assignment(self):
|
| 168 |
+
self.assertTrue(self.find_binding("a", "[a] = b"))
|
| 169 |
+
self.assertTrue(self.find_binding("a", "[a, b, c] = [b, c, d]"))
|
| 170 |
+
self.assertTrue(self.find_binding("a", "[c, [d, a], b] = foo()"))
|
| 171 |
+
self.assertTrue(self.find_binding("a", "[a, b] = foo().foo[a][foo]"))
|
| 172 |
+
self.assertFalse(self.find_binding("a", "[foo, b] = (b, a)"))
|
| 173 |
+
self.assertFalse(self.find_binding("a", "[foo, [b, c]] = (a, b, c)"))
|
| 174 |
+
|
| 175 |
+
def test_invalid_assignments(self):
|
| 176 |
+
self.assertFalse(self.find_binding("a", "foo.a = 5"))
|
| 177 |
+
self.assertFalse(self.find_binding("a", "foo[a] = 5"))
|
| 178 |
+
self.assertFalse(self.find_binding("a", "foo(a) = 5"))
|
| 179 |
+
self.assertFalse(self.find_binding("a", "foo(a, b) = 5"))
|
| 180 |
+
|
| 181 |
+
def test_simple_import(self):
|
| 182 |
+
self.assertTrue(self.find_binding("a", "import a"))
|
| 183 |
+
self.assertTrue(self.find_binding("a", "import b, c, a, d"))
|
| 184 |
+
self.assertFalse(self.find_binding("a", "import b"))
|
| 185 |
+
self.assertFalse(self.find_binding("a", "import b, c, d"))
|
| 186 |
+
|
| 187 |
+
def test_from_import(self):
|
| 188 |
+
self.assertTrue(self.find_binding("a", "from x import a"))
|
| 189 |
+
self.assertTrue(self.find_binding("a", "from a import a"))
|
| 190 |
+
self.assertTrue(self.find_binding("a", "from x import b, c, a, d"))
|
| 191 |
+
self.assertTrue(self.find_binding("a", "from x.b import a"))
|
| 192 |
+
self.assertTrue(self.find_binding("a", "from x.b import b, c, a, d"))
|
| 193 |
+
self.assertFalse(self.find_binding("a", "from a import b"))
|
| 194 |
+
self.assertFalse(self.find_binding("a", "from a.d import b"))
|
| 195 |
+
self.assertFalse(self.find_binding("a", "from d.a import b"))
|
| 196 |
+
|
| 197 |
+
def test_import_as(self):
|
| 198 |
+
self.assertTrue(self.find_binding("a", "import b as a"))
|
| 199 |
+
self.assertTrue(self.find_binding("a", "import b as a, c, a as f, d"))
|
| 200 |
+
self.assertFalse(self.find_binding("a", "import a as f"))
|
| 201 |
+
self.assertFalse(self.find_binding("a", "import b, c as f, d as e"))
|
| 202 |
+
|
| 203 |
+
def test_from_import_as(self):
|
| 204 |
+
self.assertTrue(self.find_binding("a", "from x import b as a"))
|
| 205 |
+
self.assertTrue(self.find_binding("a", "from x import g as a, d as b"))
|
| 206 |
+
self.assertTrue(self.find_binding("a", "from x.b import t as a"))
|
| 207 |
+
self.assertTrue(self.find_binding("a", "from x.b import g as a, d"))
|
| 208 |
+
self.assertFalse(self.find_binding("a", "from a import b as t"))
|
| 209 |
+
self.assertFalse(self.find_binding("a", "from a.d import b as t"))
|
| 210 |
+
self.assertFalse(self.find_binding("a", "from d.a import b as t"))
|
| 211 |
+
|
| 212 |
+
def test_simple_import_with_package(self):
|
| 213 |
+
self.assertTrue(self.find_binding("b", "import b"))
|
| 214 |
+
self.assertTrue(self.find_binding("b", "import b, c, d"))
|
| 215 |
+
self.assertFalse(self.find_binding("b", "import b", "b"))
|
| 216 |
+
self.assertFalse(self.find_binding("b", "import b, c, d", "c"))
|
| 217 |
+
|
| 218 |
+
def test_from_import_with_package(self):
|
| 219 |
+
self.assertTrue(self.find_binding("a", "from x import a", "x"))
|
| 220 |
+
self.assertTrue(self.find_binding("a", "from a import a", "a"))
|
| 221 |
+
self.assertTrue(self.find_binding("a", "from x import *", "x"))
|
| 222 |
+
self.assertTrue(self.find_binding("a", "from x import b, c, a, d", "x"))
|
| 223 |
+
self.assertTrue(self.find_binding("a", "from x.b import a", "x.b"))
|
| 224 |
+
self.assertTrue(self.find_binding("a", "from x.b import *", "x.b"))
|
| 225 |
+
self.assertTrue(self.find_binding("a", "from x.b import b, c, a, d", "x.b"))
|
| 226 |
+
self.assertFalse(self.find_binding("a", "from a import b", "a"))
|
| 227 |
+
self.assertFalse(self.find_binding("a", "from a.d import b", "a.d"))
|
| 228 |
+
self.assertFalse(self.find_binding("a", "from d.a import b", "a.d"))
|
| 229 |
+
self.assertFalse(self.find_binding("a", "from x.y import *", "a.b"))
|
| 230 |
+
|
| 231 |
+
def test_import_as_with_package(self):
|
| 232 |
+
self.assertFalse(self.find_binding("a", "import b.c as a", "b.c"))
|
| 233 |
+
self.assertFalse(self.find_binding("a", "import a as f", "f"))
|
| 234 |
+
self.assertFalse(self.find_binding("a", "import a as f", "a"))
|
| 235 |
+
|
| 236 |
+
def test_from_import_as_with_package(self):
|
| 237 |
+
# Because it would take a lot of special-case code in the fixers
|
| 238 |
+
# to deal with from foo import bar as baz, we'll simply always
|
| 239 |
+
# fail if there is an "from ... import ... as ..."
|
| 240 |
+
self.assertFalse(self.find_binding("a", "from x import b as a", "x"))
|
| 241 |
+
self.assertFalse(self.find_binding("a", "from x import g as a, d as b", "x"))
|
| 242 |
+
self.assertFalse(self.find_binding("a", "from x.b import t as a", "x.b"))
|
| 243 |
+
self.assertFalse(self.find_binding("a", "from x.b import g as a, d", "x.b"))
|
| 244 |
+
self.assertFalse(self.find_binding("a", "from a import b as t", "a"))
|
| 245 |
+
self.assertFalse(self.find_binding("a", "from a import b as t", "b"))
|
| 246 |
+
self.assertFalse(self.find_binding("a", "from a import b as t", "t"))
|
| 247 |
+
|
| 248 |
+
def test_function_def(self):
|
| 249 |
+
self.assertTrue(self.find_binding("a", "def a(): pass"))
|
| 250 |
+
self.assertTrue(self.find_binding("a", "def a(b, c, d): pass"))
|
| 251 |
+
self.assertTrue(self.find_binding("a", "def a(): b = 7"))
|
| 252 |
+
self.assertFalse(self.find_binding("a", "def d(b, (c, a), e): pass"))
|
| 253 |
+
self.assertFalse(self.find_binding("a", "def d(a=7): pass"))
|
| 254 |
+
self.assertFalse(self.find_binding("a", "def d(a): pass"))
|
| 255 |
+
self.assertFalse(self.find_binding("a", "def d(): a = 7"))
|
| 256 |
+
|
| 257 |
+
s = """
|
| 258 |
+
def d():
|
| 259 |
+
def a():
|
| 260 |
+
pass"""
|
| 261 |
+
self.assertFalse(self.find_binding("a", s))
|
| 262 |
+
|
| 263 |
+
def test_class_def(self):
|
| 264 |
+
self.assertTrue(self.find_binding("a", "class a: pass"))
|
| 265 |
+
self.assertTrue(self.find_binding("a", "class a(): pass"))
|
| 266 |
+
self.assertTrue(self.find_binding("a", "class a(b): pass"))
|
| 267 |
+
self.assertTrue(self.find_binding("a", "class a(b, c=8): pass"))
|
| 268 |
+
self.assertFalse(self.find_binding("a", "class d: pass"))
|
| 269 |
+
self.assertFalse(self.find_binding("a", "class d(a): pass"))
|
| 270 |
+
self.assertFalse(self.find_binding("a", "class d(b, a=7): pass"))
|
| 271 |
+
self.assertFalse(self.find_binding("a", "class d(b, *a): pass"))
|
| 272 |
+
self.assertFalse(self.find_binding("a", "class d(b, **a): pass"))
|
| 273 |
+
self.assertFalse(self.find_binding("a", "class d: a = 7"))
|
| 274 |
+
|
| 275 |
+
s = """
|
| 276 |
+
class d():
|
| 277 |
+
class a():
|
| 278 |
+
pass"""
|
| 279 |
+
self.assertFalse(self.find_binding("a", s))
|
| 280 |
+
|
| 281 |
+
def test_for(self):
|
| 282 |
+
self.assertTrue(self.find_binding("a", "for a in r: pass"))
|
| 283 |
+
self.assertTrue(self.find_binding("a", "for a, b in r: pass"))
|
| 284 |
+
self.assertTrue(self.find_binding("a", "for (a, b) in r: pass"))
|
| 285 |
+
self.assertTrue(self.find_binding("a", "for c, (a,) in r: pass"))
|
| 286 |
+
self.assertTrue(self.find_binding("a", "for c, (a, b) in r: pass"))
|
| 287 |
+
self.assertTrue(self.find_binding("a", "for c in r: a = c"))
|
| 288 |
+
self.assertFalse(self.find_binding("a", "for c in a: pass"))
|
| 289 |
+
|
| 290 |
+
def test_for_nested(self):
|
| 291 |
+
s = """
|
| 292 |
+
for b in r:
|
| 293 |
+
for a in b:
|
| 294 |
+
pass"""
|
| 295 |
+
self.assertTrue(self.find_binding("a", s))
|
| 296 |
+
|
| 297 |
+
s = """
|
| 298 |
+
for b in r:
|
| 299 |
+
for a, c in b:
|
| 300 |
+
pass"""
|
| 301 |
+
self.assertTrue(self.find_binding("a", s))
|
| 302 |
+
|
| 303 |
+
s = """
|
| 304 |
+
for b in r:
|
| 305 |
+
for (a, c) in b:
|
| 306 |
+
pass"""
|
| 307 |
+
self.assertTrue(self.find_binding("a", s))
|
| 308 |
+
|
| 309 |
+
s = """
|
| 310 |
+
for b in r:
|
| 311 |
+
for (a,) in b:
|
| 312 |
+
pass"""
|
| 313 |
+
self.assertTrue(self.find_binding("a", s))
|
| 314 |
+
|
| 315 |
+
s = """
|
| 316 |
+
for b in r:
|
| 317 |
+
for c, (a, d) in b:
|
| 318 |
+
pass"""
|
| 319 |
+
self.assertTrue(self.find_binding("a", s))
|
| 320 |
+
|
| 321 |
+
s = """
|
| 322 |
+
for b in r:
|
| 323 |
+
for c in b:
|
| 324 |
+
a = 7"""
|
| 325 |
+
self.assertTrue(self.find_binding("a", s))
|
| 326 |
+
|
| 327 |
+
s = """
|
| 328 |
+
for b in r:
|
| 329 |
+
for c in b:
|
| 330 |
+
d = a"""
|
| 331 |
+
self.assertFalse(self.find_binding("a", s))
|
| 332 |
+
|
| 333 |
+
s = """
|
| 334 |
+
for b in r:
|
| 335 |
+
for c in a:
|
| 336 |
+
d = 7"""
|
| 337 |
+
self.assertFalse(self.find_binding("a", s))
|
| 338 |
+
|
| 339 |
+
def test_if(self):
|
| 340 |
+
self.assertTrue(self.find_binding("a", "if b in r: a = c"))
|
| 341 |
+
self.assertFalse(self.find_binding("a", "if a in r: d = e"))
|
| 342 |
+
|
| 343 |
+
def test_if_nested(self):
|
| 344 |
+
s = """
|
| 345 |
+
if b in r:
|
| 346 |
+
if c in d:
|
| 347 |
+
a = c"""
|
| 348 |
+
self.assertTrue(self.find_binding("a", s))
|
| 349 |
+
|
| 350 |
+
s = """
|
| 351 |
+
if b in r:
|
| 352 |
+
if c in d:
|
| 353 |
+
c = a"""
|
| 354 |
+
self.assertFalse(self.find_binding("a", s))
|
| 355 |
+
|
| 356 |
+
def test_while(self):
|
| 357 |
+
self.assertTrue(self.find_binding("a", "while b in r: a = c"))
|
| 358 |
+
self.assertFalse(self.find_binding("a", "while a in r: d = e"))
|
| 359 |
+
|
| 360 |
+
def test_while_nested(self):
|
| 361 |
+
s = """
|
| 362 |
+
while b in r:
|
| 363 |
+
while c in d:
|
| 364 |
+
a = c"""
|
| 365 |
+
self.assertTrue(self.find_binding("a", s))
|
| 366 |
+
|
| 367 |
+
s = """
|
| 368 |
+
while b in r:
|
| 369 |
+
while c in d:
|
| 370 |
+
c = a"""
|
| 371 |
+
self.assertFalse(self.find_binding("a", s))
|
| 372 |
+
|
| 373 |
+
def test_try_except(self):
|
| 374 |
+
s = """
|
| 375 |
+
try:
|
| 376 |
+
a = 6
|
| 377 |
+
except:
|
| 378 |
+
b = 8"""
|
| 379 |
+
self.assertTrue(self.find_binding("a", s))
|
| 380 |
+
|
| 381 |
+
s = """
|
| 382 |
+
try:
|
| 383 |
+
b = 8
|
| 384 |
+
except:
|
| 385 |
+
a = 6"""
|
| 386 |
+
self.assertTrue(self.find_binding("a", s))
|
| 387 |
+
|
| 388 |
+
s = """
|
| 389 |
+
try:
|
| 390 |
+
b = 8
|
| 391 |
+
except KeyError:
|
| 392 |
+
pass
|
| 393 |
+
except:
|
| 394 |
+
a = 6"""
|
| 395 |
+
self.assertTrue(self.find_binding("a", s))
|
| 396 |
+
|
| 397 |
+
s = """
|
| 398 |
+
try:
|
| 399 |
+
b = 8
|
| 400 |
+
except:
|
| 401 |
+
b = 6"""
|
| 402 |
+
self.assertFalse(self.find_binding("a", s))
|
| 403 |
+
|
| 404 |
+
def test_try_except_nested(self):
|
| 405 |
+
s = """
|
| 406 |
+
try:
|
| 407 |
+
try:
|
| 408 |
+
a = 6
|
| 409 |
+
except:
|
| 410 |
+
pass
|
| 411 |
+
except:
|
| 412 |
+
b = 8"""
|
| 413 |
+
self.assertTrue(self.find_binding("a", s))
|
| 414 |
+
|
| 415 |
+
s = """
|
| 416 |
+
try:
|
| 417 |
+
b = 8
|
| 418 |
+
except:
|
| 419 |
+
try:
|
| 420 |
+
a = 6
|
| 421 |
+
except:
|
| 422 |
+
pass"""
|
| 423 |
+
self.assertTrue(self.find_binding("a", s))
|
| 424 |
+
|
| 425 |
+
s = """
|
| 426 |
+
try:
|
| 427 |
+
b = 8
|
| 428 |
+
except:
|
| 429 |
+
try:
|
| 430 |
+
pass
|
| 431 |
+
except:
|
| 432 |
+
a = 6"""
|
| 433 |
+
self.assertTrue(self.find_binding("a", s))
|
| 434 |
+
|
| 435 |
+
s = """
|
| 436 |
+
try:
|
| 437 |
+
try:
|
| 438 |
+
b = 8
|
| 439 |
+
except KeyError:
|
| 440 |
+
pass
|
| 441 |
+
except:
|
| 442 |
+
a = 6
|
| 443 |
+
except:
|
| 444 |
+
pass"""
|
| 445 |
+
self.assertTrue(self.find_binding("a", s))
|
| 446 |
+
|
| 447 |
+
s = """
|
| 448 |
+
try:
|
| 449 |
+
pass
|
| 450 |
+
except:
|
| 451 |
+
try:
|
| 452 |
+
b = 8
|
| 453 |
+
except KeyError:
|
| 454 |
+
pass
|
| 455 |
+
except:
|
| 456 |
+
a = 6"""
|
| 457 |
+
self.assertTrue(self.find_binding("a", s))
|
| 458 |
+
|
| 459 |
+
s = """
|
| 460 |
+
try:
|
| 461 |
+
b = 8
|
| 462 |
+
except:
|
| 463 |
+
b = 6"""
|
| 464 |
+
self.assertFalse(self.find_binding("a", s))
|
| 465 |
+
|
| 466 |
+
s = """
|
| 467 |
+
try:
|
| 468 |
+
try:
|
| 469 |
+
b = 8
|
| 470 |
+
except:
|
| 471 |
+
c = d
|
| 472 |
+
except:
|
| 473 |
+
try:
|
| 474 |
+
b = 6
|
| 475 |
+
except:
|
| 476 |
+
t = 8
|
| 477 |
+
except:
|
| 478 |
+
o = y"""
|
| 479 |
+
self.assertFalse(self.find_binding("a", s))
|
| 480 |
+
|
| 481 |
+
def test_try_except_finally(self):
|
| 482 |
+
s = """
|
| 483 |
+
try:
|
| 484 |
+
c = 6
|
| 485 |
+
except:
|
| 486 |
+
b = 8
|
| 487 |
+
finally:
|
| 488 |
+
a = 9"""
|
| 489 |
+
self.assertTrue(self.find_binding("a", s))
|
| 490 |
+
|
| 491 |
+
s = """
|
| 492 |
+
try:
|
| 493 |
+
b = 8
|
| 494 |
+
finally:
|
| 495 |
+
a = 6"""
|
| 496 |
+
self.assertTrue(self.find_binding("a", s))
|
| 497 |
+
|
| 498 |
+
s = """
|
| 499 |
+
try:
|
| 500 |
+
b = 8
|
| 501 |
+
finally:
|
| 502 |
+
b = 6"""
|
| 503 |
+
self.assertFalse(self.find_binding("a", s))
|
| 504 |
+
|
| 505 |
+
s = """
|
| 506 |
+
try:
|
| 507 |
+
b = 8
|
| 508 |
+
except:
|
| 509 |
+
b = 9
|
| 510 |
+
finally:
|
| 511 |
+
b = 6"""
|
| 512 |
+
self.assertFalse(self.find_binding("a", s))
|
| 513 |
+
|
| 514 |
+
def test_try_except_finally_nested(self):
|
| 515 |
+
s = """
|
| 516 |
+
try:
|
| 517 |
+
c = 6
|
| 518 |
+
except:
|
| 519 |
+
b = 8
|
| 520 |
+
finally:
|
| 521 |
+
try:
|
| 522 |
+
a = 9
|
| 523 |
+
except:
|
| 524 |
+
b = 9
|
| 525 |
+
finally:
|
| 526 |
+
c = 9"""
|
| 527 |
+
self.assertTrue(self.find_binding("a", s))
|
| 528 |
+
|
| 529 |
+
s = """
|
| 530 |
+
try:
|
| 531 |
+
b = 8
|
| 532 |
+
finally:
|
| 533 |
+
try:
|
| 534 |
+
pass
|
| 535 |
+
finally:
|
| 536 |
+
a = 6"""
|
| 537 |
+
self.assertTrue(self.find_binding("a", s))
|
| 538 |
+
|
| 539 |
+
s = """
|
| 540 |
+
try:
|
| 541 |
+
b = 8
|
| 542 |
+
finally:
|
| 543 |
+
try:
|
| 544 |
+
b = 6
|
| 545 |
+
finally:
|
| 546 |
+
b = 7"""
|
| 547 |
+
self.assertFalse(self.find_binding("a", s))
|
| 548 |
+
|
| 549 |
+
class Test_touch_import(support.TestCase):
|
| 550 |
+
|
| 551 |
+
def test_after_docstring(self):
|
| 552 |
+
node = parse('"""foo"""\nbar()')
|
| 553 |
+
fixer_util.touch_import(None, "foo", node)
|
| 554 |
+
self.assertEqual(str(node), '"""foo"""\nimport foo\nbar()\n\n')
|
| 555 |
+
|
| 556 |
+
def test_after_imports(self):
|
| 557 |
+
node = parse('"""foo"""\nimport bar\nbar()')
|
| 558 |
+
fixer_util.touch_import(None, "foo", node)
|
| 559 |
+
self.assertEqual(str(node), '"""foo"""\nimport bar\nimport foo\nbar()\n\n')
|
| 560 |
+
|
| 561 |
+
def test_beginning(self):
|
| 562 |
+
node = parse('bar()')
|
| 563 |
+
fixer_util.touch_import(None, "foo", node)
|
| 564 |
+
self.assertEqual(str(node), 'import foo\nbar()\n\n')
|
| 565 |
+
|
| 566 |
+
def test_from_import(self):
|
| 567 |
+
node = parse('bar()')
|
| 568 |
+
fixer_util.touch_import("html", "escape", node)
|
| 569 |
+
self.assertEqual(str(node), 'from html import escape\nbar()\n\n')
|
| 570 |
+
|
| 571 |
+
def test_name_import(self):
|
| 572 |
+
node = parse('bar()')
|
| 573 |
+
fixer_util.touch_import(None, "cgi", node)
|
| 574 |
+
self.assertEqual(str(node), 'import cgi\nbar()\n\n')
|
| 575 |
+
|
| 576 |
+
class Test_find_indentation(support.TestCase):
|
| 577 |
+
|
| 578 |
+
def test_nothing(self):
|
| 579 |
+
fi = fixer_util.find_indentation
|
| 580 |
+
node = parse("node()")
|
| 581 |
+
self.assertEqual(fi(node), "")
|
| 582 |
+
node = parse("")
|
| 583 |
+
self.assertEqual(fi(node), "")
|
| 584 |
+
|
| 585 |
+
def test_simple(self):
|
| 586 |
+
fi = fixer_util.find_indentation
|
| 587 |
+
node = parse("def f():\n x()")
|
| 588 |
+
self.assertEqual(fi(node), "")
|
| 589 |
+
self.assertEqual(fi(node.children[0].children[4].children[2]), " ")
|
| 590 |
+
node = parse("def f():\n x()\n y()")
|
| 591 |
+
self.assertEqual(fi(node.children[0].children[4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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2001-2019 by Vinay Sajip. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Permission to use, copy, modify, and distribute this software and its
|
| 4 |
+
# documentation for any purpose and without fee is hereby granted,
|
| 5 |
+
# provided that the above copyright notice appear in all copies and that
|
| 6 |
+
# both that copyright notice and this permission notice appear in
|
| 7 |
+
# supporting documentation, and that the name of Vinay Sajip
|
| 8 |
+
# not be used in advertising or publicity pertaining to distribution
|
| 9 |
+
# of the software without specific, written prior permission.
|
| 10 |
+
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
|
| 11 |
+
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
|
| 12 |
+
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
|
| 13 |
+
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
|
| 14 |
+
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 15 |
+
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
Logging package for Python. Based on PEP 282 and comments thereto in
|
| 19 |
+
comp.lang.python.
|
| 20 |
+
|
| 21 |
+
Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
|
| 22 |
+
|
| 23 |
+
To use, simply 'import logging' and log away!
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import sys, os, time, io, re, traceback, warnings, weakref, collections.abc
|
| 27 |
+
|
| 28 |
+
from string import Template
|
| 29 |
+
from string import Formatter as StrFormatter
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
__all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR',
|
| 33 |
+
'FATAL', 'FileHandler', 'Filter', 'Formatter', 'Handler', 'INFO',
|
| 34 |
+
'LogRecord', 'Logger', 'LoggerAdapter', 'NOTSET', 'NullHandler',
|
| 35 |
+
'StreamHandler', 'WARN', 'WARNING', 'addLevelName', 'basicConfig',
|
| 36 |
+
'captureWarnings', 'critical', 'debug', 'disable', 'error',
|
| 37 |
+
'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
|
| 38 |
+
'info', 'log', 'makeLogRecord', 'setLoggerClass', 'shutdown',
|
| 39 |
+
'warn', 'warning', 'getLogRecordFactory', 'setLogRecordFactory',
|
| 40 |
+
'lastResort', 'raiseExceptions']
|
| 41 |
+
|
| 42 |
+
import threading
|
| 43 |
+
|
| 44 |
+
__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
|
| 45 |
+
__status__ = "production"
|
| 46 |
+
# The following module attributes are no longer updated.
|
| 47 |
+
__version__ = "0.5.1.2"
|
| 48 |
+
__date__ = "07 February 2010"
|
| 49 |
+
|
| 50 |
+
#---------------------------------------------------------------------------
|
| 51 |
+
# Miscellaneous module data
|
| 52 |
+
#---------------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
#
|
| 55 |
+
#_startTime is used as the base when calculating the relative time of events
|
| 56 |
+
#
|
| 57 |
+
_startTime = time.time()
|
| 58 |
+
|
| 59 |
+
#
|
| 60 |
+
#raiseExceptions is used to see if exceptions during handling should be
|
| 61 |
+
#propagated
|
| 62 |
+
#
|
| 63 |
+
raiseExceptions = True
|
| 64 |
+
|
| 65 |
+
#
|
| 66 |
+
# If you don't want threading information in the log, set this to zero
|
| 67 |
+
#
|
| 68 |
+
logThreads = True
|
| 69 |
+
|
| 70 |
+
#
|
| 71 |
+
# If you don't want multiprocessing information in the log, set this to zero
|
| 72 |
+
#
|
| 73 |
+
logMultiprocessing = True
|
| 74 |
+
|
| 75 |
+
#
|
| 76 |
+
# If you don't want process information in the log, set this to zero
|
| 77 |
+
#
|
| 78 |
+
logProcesses = True
|
| 79 |
+
|
| 80 |
+
#---------------------------------------------------------------------------
|
| 81 |
+
# Level related stuff
|
| 82 |
+
#---------------------------------------------------------------------------
|
| 83 |
+
#
|
| 84 |
+
# Default levels and level names, these can be replaced with any positive set
|
| 85 |
+
# of values having corresponding names. There is a pseudo-level, NOTSET, which
|
| 86 |
+
# is only really there as a lower limit for user-defined levels. Handlers and
|
| 87 |
+
# loggers are initialized with NOTSET so that they will log all messages, even
|
| 88 |
+
# at user-defined levels.
|
| 89 |
+
#
|
| 90 |
+
|
| 91 |
+
CRITICAL = 50
|
| 92 |
+
FATAL = CRITICAL
|
| 93 |
+
ERROR = 40
|
| 94 |
+
WARNING = 30
|
| 95 |
+
WARN = WARNING
|
| 96 |
+
INFO = 20
|
| 97 |
+
DEBUG = 10
|
| 98 |
+
NOTSET = 0
|
| 99 |
+
|
| 100 |
+
_levelToName = {
|
| 101 |
+
CRITICAL: 'CRITICAL',
|
| 102 |
+
ERROR: 'ERROR',
|
| 103 |
+
WARNING: 'WARNING',
|
| 104 |
+
INFO: 'INFO',
|
| 105 |
+
DEBUG: 'DEBUG',
|
| 106 |
+
NOTSET: 'NOTSET',
|
| 107 |
+
}
|
| 108 |
+
_nameToLevel = {
|
| 109 |
+
'CRITICAL': CRITICAL,
|
| 110 |
+
'FATAL': FATAL,
|
| 111 |
+
'ERROR': ERROR,
|
| 112 |
+
'WARN': WARNING,
|
| 113 |
+
'WARNING': WARNING,
|
| 114 |
+
'INFO': INFO,
|
| 115 |
+
'DEBUG': DEBUG,
|
| 116 |
+
'NOTSET': NOTSET,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
def getLevelName(level):
|
| 120 |
+
"""
|
| 121 |
+
Return the textual or numeric representation of logging level 'level'.
|
| 122 |
+
|
| 123 |
+
If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
|
| 124 |
+
INFO, DEBUG) then you get the corresponding string. If you have
|
| 125 |
+
associated levels with names using addLevelName then the name you have
|
| 126 |
+
associated with 'level' is returned.
|
| 127 |
+
|
| 128 |
+
If a numeric value corresponding to one of the defined levels is passed
|
| 129 |
+
in, the corresponding string representation is returned.
|
| 130 |
+
|
| 131 |
+
If a string representation of the level is passed in, the corresponding
|
| 132 |
+
numeric value is returned.
|
| 133 |
+
|
| 134 |
+
If no matching numeric or string value is passed in, the string
|
| 135 |
+
'Level %s' % level is returned.
|
| 136 |
+
"""
|
| 137 |
+
# See Issues #22386, #27937 and #29220 for why it's this way
|
| 138 |
+
result = _levelToName.get(level)
|
| 139 |
+
if result is not None:
|
| 140 |
+
return result
|
| 141 |
+
result = _nameToLevel.get(level)
|
| 142 |
+
if result is not None:
|
| 143 |
+
return result
|
| 144 |
+
return "Level %s" % level
|
| 145 |
+
|
| 146 |
+
def addLevelName(level, levelName):
|
| 147 |
+
"""
|
| 148 |
+
Associate 'levelName' with 'level'.
|
| 149 |
+
|
| 150 |
+
This is used when converting levels to text during message formatting.
|
| 151 |
+
"""
|
| 152 |
+
_acquireLock()
|
| 153 |
+
try: #unlikely to cause an exception, but you never know...
|
| 154 |
+
_levelToName[level] = levelName
|
| 155 |
+
_nameToLevel[levelName] = level
|
| 156 |
+
finally:
|
| 157 |
+
_releaseLock()
|
| 158 |
+
|
| 159 |
+
if hasattr(sys, '_getframe'):
|
| 160 |
+
currentframe = lambda: sys._getframe(3)
|
| 161 |
+
else: #pragma: no cover
|
| 162 |
+
def currentframe():
|
| 163 |
+
"""Return the frame object for the caller's stack frame."""
|
| 164 |
+
try:
|
| 165 |
+
raise Exception
|
| 166 |
+
except Exception:
|
| 167 |
+
return sys.exc_info()[2].tb_frame.f_back
|
| 168 |
+
|
| 169 |
+
#
|
| 170 |
+
# _srcfile is used when walking the stack to check when we've got the first
|
| 171 |
+
# caller stack frame, by skipping frames whose filename is that of this
|
| 172 |
+
# module's source. It therefore should contain the filename of this module's
|
| 173 |
+
# source file.
|
| 174 |
+
#
|
| 175 |
+
# Ordinarily we would use __file__ for this, but frozen modules don't always
|
| 176 |
+
# have __file__ set, for some reason (see Issue #21736). Thus, we get the
|
| 177 |
+
# filename from a handy code object from a function defined in this module.
|
| 178 |
+
# (There's no particular reason for picking addLevelName.)
|
| 179 |
+
#
|
| 180 |
+
|
| 181 |
+
_srcfile = os.path.normcase(addLevelName.__code__.co_filename)
|
| 182 |
+
|
| 183 |
+
# _srcfile is only used in conjunction with sys._getframe().
|
| 184 |
+
# To provide compatibility with older versions of Python, set _srcfile
|
| 185 |
+
# to None if _getframe() is not available; this value will prevent
|
| 186 |
+
# findCaller() from being called. You can also do this if you want to avoid
|
| 187 |
+
# the overhead of fetching caller information, even when _getframe() is
|
| 188 |
+
# available.
|
| 189 |
+
#if not hasattr(sys, '_getframe'):
|
| 190 |
+
# _srcfile = None
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _checkLevel(level):
|
| 194 |
+
if isinstance(level, int):
|
| 195 |
+
rv = level
|
| 196 |
+
elif str(level) == level:
|
| 197 |
+
if level not in _nameToLevel:
|
| 198 |
+
raise ValueError("Unknown level: %r" % level)
|
| 199 |
+
rv = _nameToLevel[level]
|
| 200 |
+
else:
|
| 201 |
+
raise TypeError("Level not an integer or a valid string: %r"
|
| 202 |
+
% (level,))
|
| 203 |
+
return rv
|
| 204 |
+
|
| 205 |
+
#---------------------------------------------------------------------------
|
| 206 |
+
# Thread-related stuff
|
| 207 |
+
#---------------------------------------------------------------------------
|
| 208 |
+
|
| 209 |
+
#
|
| 210 |
+
#_lock is used to serialize access to shared data structures in this module.
|
| 211 |
+
#This needs to be an RLock because fileConfig() creates and configures
|
| 212 |
+
#Handlers, and so might arbitrary user threads. Since Handler code updates the
|
| 213 |
+
#shared dictionary _handlers, it needs to acquire the lock. But if configuring,
|
| 214 |
+
#the lock would already have been acquired - so we need an RLock.
|
| 215 |
+
#The same argument applies to Loggers and Manager.loggerDict.
|
| 216 |
+
#
|
| 217 |
+
_lock = threading.RLock()
|
| 218 |
+
|
| 219 |
+
def _acquireLock():
|
| 220 |
+
"""
|
| 221 |
+
Acquire the module-level lock for serializing access to shared data.
|
| 222 |
+
|
| 223 |
+
This should be released with _releaseLock().
|
| 224 |
+
"""
|
| 225 |
+
if _lock:
|
| 226 |
+
_lock.acquire()
|
| 227 |
+
|
| 228 |
+
def _releaseLock():
|
| 229 |
+
"""
|
| 230 |
+
Release the module-level lock acquired by calling _acquireLock().
|
| 231 |
+
"""
|
| 232 |
+
if _lock:
|
| 233 |
+
_lock.release()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
# Prevent a held logging lock from blocking a child from logging.
|
| 237 |
+
|
| 238 |
+
if not hasattr(os, 'register_at_fork'): # Windows and friends.
|
| 239 |
+
def _register_at_fork_reinit_lock(instance):
|
| 240 |
+
pass # no-op when os.register_at_fork does not exist.
|
| 241 |
+
else:
|
| 242 |
+
# A collection of instances with a _at_fork_reinit method (logging.Handler)
|
| 243 |
+
# to be called in the child after forking. The weakref avoids us keeping
|
| 244 |
+
# discarded Handler instances alive.
|
| 245 |
+
_at_fork_reinit_lock_weakset = weakref.WeakSet()
|
| 246 |
+
|
| 247 |
+
def _register_at_fork_reinit_lock(instance):
|
| 248 |
+
_acquireLock()
|
| 249 |
+
try:
|
| 250 |
+
_at_fork_reinit_lock_weakset.add(instance)
|
| 251 |
+
finally:
|
| 252 |
+
_releaseLock()
|
| 253 |
+
|
| 254 |
+
def _after_at_fork_child_reinit_locks():
|
| 255 |
+
for handler in _at_fork_reinit_lock_weakset:
|
| 256 |
+
handler._at_fork_reinit()
|
| 257 |
+
|
| 258 |
+
# _acquireLock() was called in the parent before forking.
|
| 259 |
+
# The lock is reinitialized to unlocked state.
|
| 260 |
+
_lock._at_fork_reinit()
|
| 261 |
+
|
| 262 |
+
os.register_at_fork(before=_acquireLock,
|
| 263 |
+
after_in_child=_after_at_fork_child_reinit_locks,
|
| 264 |
+
after_in_parent=_releaseLock)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
#---------------------------------------------------------------------------
|
| 268 |
+
# The logging record
|
| 269 |
+
#---------------------------------------------------------------------------
|
| 270 |
+
|
| 271 |
+
class LogRecord(object):
|
| 272 |
+
"""
|
| 273 |
+
A LogRecord instance represents an event being logged.
|
| 274 |
+
|
| 275 |
+
LogRecord instances are created every time something is logged. They
|
| 276 |
+
contain all the information pertinent to the event being logged. The
|
| 277 |
+
main information passed in is in msg and args, which are combined
|
| 278 |
+
using str(msg) % args to create the message field of the record. The
|
| 279 |
+
record also includes information such as when the record was created,
|
| 280 |
+
the source line where the logging call was made, and any exception
|
| 281 |
+
information to be logged.
|
| 282 |
+
"""
|
| 283 |
+
def __init__(self, name, level, pathname, lineno,
|
| 284 |
+
msg, args, exc_info, func=None, sinfo=None, **kwargs):
|
| 285 |
+
"""
|
| 286 |
+
Initialize a logging record with interesting information.
|
| 287 |
+
"""
|
| 288 |
+
ct = time.time()
|
| 289 |
+
self.name = name
|
| 290 |
+
self.msg = msg
|
| 291 |
+
#
|
| 292 |
+
# The following statement allows passing of a dictionary as a sole
|
| 293 |
+
# argument, so that you can do something like
|
| 294 |
+
# logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
|
| 295 |
+
# Suggested by Stefan Behnel.
|
| 296 |
+
# Note that without the test for args[0], we get a problem because
|
| 297 |
+
# during formatting, we test to see if the arg is present using
|
| 298 |
+
# 'if self.args:'. If the event being logged is e.g. 'Value is %d'
|
| 299 |
+
# and if the passed arg fails 'if self.args:' then no formatting
|
| 300 |
+
# is done. For example, logger.warning('Value is %d', 0) would log
|
| 301 |
+
# 'Value is %d' instead of 'Value is 0'.
|
| 302 |
+
# For the use case of passing a dictionary, this should not be a
|
| 303 |
+
# problem.
|
| 304 |
+
# Issue #21172: a request was made to relax the isinstance check
|
| 305 |
+
# to hasattr(args[0], '__getitem__'). However, the docs on string
|
| 306 |
+
# formatting still seem to suggest a mapping object is required.
|
| 307 |
+
# Thus, while not removing the isinstance check, it does now look
|
| 308 |
+
# for collections.abc.Mapping rather than, as before, dict.
|
| 309 |
+
if (args and len(args) == 1 and isinstance(args[0], collections.abc.Mapping)
|
| 310 |
+
and args[0]):
|
| 311 |
+
args = args[0]
|
| 312 |
+
self.args = args
|
| 313 |
+
self.levelname = getLevelName(level)
|
| 314 |
+
self.levelno = level
|
| 315 |
+
self.pathname = pathname
|
| 316 |
+
try:
|
| 317 |
+
self.filename = os.path.basename(pathname)
|
| 318 |
+
self.module = os.path.splitext(self.filename)[0]
|
| 319 |
+
except (TypeError, ValueError, AttributeError):
|
| 320 |
+
self.filename = pathname
|
| 321 |
+
self.module = "Unknown module"
|
| 322 |
+
self.exc_info = exc_info
|
| 323 |
+
self.exc_text = None # used to cache the traceback text
|
| 324 |
+
self.stack_info = sinfo
|
| 325 |
+
self.lineno = lineno
|
| 326 |
+
self.funcName = func
|
| 327 |
+
self.created = ct
|
| 328 |
+
self.msecs = int((ct - int(ct)) * 1000) + 0.0 # see gh-89047
|
| 329 |
+
self.relativeCreated = (self.created - _startTime) * 1000
|
| 330 |
+
if logThreads:
|
| 331 |
+
self.thread = threading.get_ident()
|
| 332 |
+
self.threadName = threading.current_thread().name
|
| 333 |
+
else: # pragma: no cover
|
| 334 |
+
self.thread = None
|
| 335 |
+
self.threadName = None
|
| 336 |
+
if not logMultiprocessing: # pragma: no cover
|
| 337 |
+
self.processName = None
|
| 338 |
+
else:
|
| 339 |
+
self.processName = 'MainProcess'
|
| 340 |
+
mp = sys.modules.get('multiprocessing')
|
| 341 |
+
if mp is not None:
|
| 342 |
+
# Errors may occur if multiprocessing has not finished loading
|
| 343 |
+
# yet - e.g. if a custom import hook causes third-party code
|
| 344 |
+
# to run when multiprocessing calls import. See issue 8200
|
| 345 |
+
# for an example
|
| 346 |
+
try:
|
| 347 |
+
self.processName = mp.current_process().name
|
| 348 |
+
except Exception: #pragma: no cover
|
| 349 |
+
pass
|
| 350 |
+
if logProcesses and hasattr(os, 'getpid'):
|
| 351 |
+
self.process = os.getpid()
|
| 352 |
+
else:
|
| 353 |
+
self.process = None
|
| 354 |
+
|
| 355 |
+
def __repr__(self):
|
| 356 |
+
return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
|
| 357 |
+
self.pathname, self.lineno, self.msg)
|
| 358 |
+
|
| 359 |
+
def getMessage(self):
|
| 360 |
+
"""
|
| 361 |
+
Return the message for this LogRecord.
|
| 362 |
+
|
| 363 |
+
Return the message for this LogRecord after merging any user-supplied
|
| 364 |
+
arguments with the message.
|
| 365 |
+
"""
|
| 366 |
+
msg = str(self.msg)
|
| 367 |
+
if self.args:
|
| 368 |
+
msg = msg % self.args
|
| 369 |
+
return msg
|
| 370 |
+
|
| 371 |
+
#
|
| 372 |
+
# Determine which class to use when instantiating log records.
|
| 373 |
+
#
|
| 374 |
+
_logRecordFactory = LogRecord
|
| 375 |
+
|
| 376 |
+
def setLogRecordFactory(factory):
|
| 377 |
+
"""
|
| 378 |
+
Set the factory to be used when instantiating a log record.
|
| 379 |
+
|
| 380 |
+
:param factory: A callable which will be called to instantiate
|
| 381 |
+
a log record.
|
| 382 |
+
"""
|
| 383 |
+
global _logRecordFactory
|
| 384 |
+
_logRecordFactory = factory
|
| 385 |
+
|
| 386 |
+
def getLogRecordFactory():
|
| 387 |
+
"""
|
| 388 |
+
Return the factory to be used when instantiating a log record.
|
| 389 |
+
"""
|
| 390 |
+
|
| 391 |
+
return _logRecordFactory
|
| 392 |
+
|
| 393 |
+
def makeLogRecord(dict):
|
| 394 |
+
"""
|
| 395 |
+
Make a LogRecord whose attributes are defined by the specified dictionary,
|
| 396 |
+
This function is useful for converting a logging event received over
|
| 397 |
+
a socket connection (which is sent as a dictionary) into a LogRecord
|
| 398 |
+
instance.
|
| 399 |
+
"""
|
| 400 |
+
rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
|
| 401 |
+
rv.__dict__.update(dict)
|
| 402 |
+
return rv
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
#---------------------------------------------------------------------------
|
| 406 |
+
# Formatter classes and functions
|
| 407 |
+
#---------------------------------------------------------------------------
|
| 408 |
+
_str_formatter = StrFormatter()
|
| 409 |
+
del StrFormatter
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class PercentStyle(object):
|
| 413 |
+
|
| 414 |
+
default_format = '%(message)s'
|
| 415 |
+
asctime_format = '%(asctime)s'
|
| 416 |
+
asctime_search = '%(asctime)'
|
| 417 |
+
validation_pattern = re.compile(r'%\(\w+\)[#0+ -]*(\*|\d+)?(\.(\*|\d+))?[diouxefgcrsa%]', re.I)
|
| 418 |
+
|
| 419 |
+
def __init__(self, fmt, *, defaults=None):
|
| 420 |
+
self._fmt = fmt or self.default_format
|
| 421 |
+
self._defaults = defaults
|
| 422 |
+
|
| 423 |
+
def usesTime(self):
|
| 424 |
+
return self._fmt.find(self.asctime_search) >= 0
|
| 425 |
+
|
| 426 |
+
def validate(self):
|
| 427 |
+
"""Validate the input format, ensure it matches the correct style"""
|
| 428 |
+
if not self.validation_pattern.search(self._fmt):
|
| 429 |
+
raise ValueError("Invalid format '%s' for '%s' style" % (self._fmt, self.default_format[0]))
|
| 430 |
+
|
| 431 |
+
def _format(self, record):
|
| 432 |
+
if defaults := self._defaults:
|
| 433 |
+
values = defaults | record.__dict__
|
| 434 |
+
else:
|
| 435 |
+
values = record.__dict__
|
| 436 |
+
return self._fmt % values
|
| 437 |
+
|
| 438 |
+
def format(self, record):
|
| 439 |
+
try:
|
| 440 |
+
return self._format(record)
|
| 441 |
+
except KeyError as e:
|
| 442 |
+
raise ValueError('Formatting field not found in record: %s' % e)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class StrFormatStyle(PercentStyle):
|
| 446 |
+
default_format = '{message}'
|
| 447 |
+
asctime_format = '{asctime}'
|
| 448 |
+
asctime_search = '{asctime'
|
| 449 |
+
|
| 450 |
+
fmt_spec = re.compile(r'^(.?[<>=^])?[+ -]?#?0?(\d+|{\w+})?[,_]?(\.(\d+|{\w+}))?[bcdefgnosx%]?$', re.I)
|
| 451 |
+
field_spec = re.compile(r'^(\d+|\w+)(\.\w+|\[[^]]+\])*$')
|
| 452 |
+
|
| 453 |
+
def _format(self, record):
|
| 454 |
+
if defaults := self._defaults:
|
| 455 |
+
values = defaults | record.__dict__
|
| 456 |
+
else:
|
| 457 |
+
values = record.__dict__
|
| 458 |
+
return self._fmt.format(**values)
|
| 459 |
+
|
| 460 |
+
def validate(self):
|
| 461 |
+
"""Validate the input format, ensure it is the correct string formatting style"""
|
| 462 |
+
fields = set()
|
| 463 |
+
try:
|
| 464 |
+
for _, fieldname, spec, conversion in _str_formatter.parse(self._fmt):
|
| 465 |
+
if fieldname:
|
| 466 |
+
if not self.field_spec.match(fieldname):
|
| 467 |
+
raise ValueError('invalid field name/expression: %r' % fieldname)
|
| 468 |
+
fields.add(fieldname)
|
| 469 |
+
if conversion and conversion not in 'rsa':
|
| 470 |
+
raise ValueError('invalid conversion: %r' % conversion)
|
| 471 |
+
if spec and not self.fmt_spec.match(spec):
|
| 472 |
+
raise ValueError('bad specifier: %r' % spec)
|
| 473 |
+
except ValueError as e:
|
| 474 |
+
raise ValueError('invalid format: %s' % e)
|
| 475 |
+
if not fields:
|
| 476 |
+
raise ValueError('invalid format: no fields')
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
class StringTemplateStyle(PercentStyle):
|
| 480 |
+
default_format = '${message}'
|
| 481 |
+
asctime_format = '${asctime}'
|
| 482 |
+
asctime_search = '${asctime}'
|
| 483 |
+
|
| 484 |
+
def __init__(self, *args, **kwargs):
|
| 485 |
+
super().__init__(*args, **kwargs)
|
| 486 |
+
self._tpl = Template(self._fmt)
|
| 487 |
+
|
| 488 |
+
def usesTime(self):
|
| 489 |
+
fmt = self._fmt
|
| 490 |
+
return fmt.find('$asctime') >= 0 or fmt.find(self.asctime_search) >= 0
|
| 491 |
+
|
| 492 |
+
def validate(self):
|
| 493 |
+
pattern = Template.pattern
|
| 494 |
+
fields = set()
|
| 495 |
+
for m in pattern.finditer(self._fmt):
|
| 496 |
+
d = m.groupdict()
|
| 497 |
+
if d['named']:
|
| 498 |
+
fields.add(d['named'])
|
| 499 |
+
elif d['braced']:
|
| 500 |
+
fields.add(d['braced'])
|
| 501 |
+
elif m.group(0) == '$':
|
| 502 |
+
raise ValueError('invalid format: bare \'$\' not allowed')
|
| 503 |
+
if not fields:
|
| 504 |
+
raise ValueError('invalid format: no fields')
|
| 505 |
+
|
| 506 |
+
def _format(self, record):
|
| 507 |
+
if defaults := self._defaults:
|
| 508 |
+
values = defaults | record.__dict__
|
| 509 |
+
else:
|
| 510 |
+
values = record.__dict__
|
| 511 |
+
return self._tpl.substitute(**values)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
|
| 515 |
+
|
| 516 |
+
_STYLES = {
|
| 517 |
+
'%': (PercentStyle, BASIC_FORMAT),
|
| 518 |
+
'{': (StrFormatStyle, '{levelname}:{name}:{message}'),
|
| 519 |
+
'$': (StringTemplateStyle, '${levelname}:${name}:${message}'),
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
class Formatter(object):
|
| 523 |
+
"""
|
| 524 |
+
Formatter instances are used to convert a LogRecord to text.
|
| 525 |
+
|
| 526 |
+
Formatters need to know how a LogRecord is constructed. They are
|
| 527 |
+
responsible for converting a LogRecord to (usually) a string which can
|
| 528 |
+
be interpreted by either a human or an external system. The base Formatter
|
| 529 |
+
allows a formatting string to be specified. If none is supplied, the
|
| 530 |
+
style-dependent default value, "%(message)s", "{message}", or
|
| 531 |
+
"${message}", is used.
|
| 532 |
+
|
| 533 |
+
The Formatter can be initialized with a format string which makes use of
|
| 534 |
+
knowledge of the LogRecord attributes - e.g. the default value mentioned
|
| 535 |
+
above makes use of the fact that the user's message and arguments are pre-
|
| 536 |
+
formatted into a LogRecord's message attribute. Currently, the useful
|
| 537 |
+
attributes in a LogRecord are described by:
|
| 538 |
+
|
| 539 |
+
%(name)s Name of the logger (logging channel)
|
| 540 |
+
%(levelno)s Numeric logging level for the message (DEBUG, INFO,
|
| 541 |
+
WARNING, ERROR, CRITICAL)
|
| 542 |
+
%(levelname)s Text logging level for the message ("DEBUG", "INFO",
|
| 543 |
+
"WARNING", "ERROR", "CRITICAL")
|
| 544 |
+
%(pathname)s Full pathname of the source file where the logging
|
| 545 |
+
call was issued (if available)
|
| 546 |
+
%(filename)s Filename portion of pathname
|
| 547 |
+
%(module)s Module (name portion of filename)
|
| 548 |
+
%(lineno)d Source line number where the logging call was issued
|
| 549 |
+
(if available)
|
| 550 |
+
%(funcName)s Function name
|
| 551 |
+
%(created)f Time when the LogRecord was created (time.time()
|
| 552 |
+
return value)
|
| 553 |
+
%(asctime)s Textual time when the LogRecord was created
|
| 554 |
+
%(msecs)d Millisecond portion of the creation time
|
| 555 |
+
%(relativeCreated)d Time in milliseconds when the LogRecord was created,
|
| 556 |
+
relative to the time the logging module was loaded
|
| 557 |
+
(typically at application startup time)
|
| 558 |
+
%(thread)d Thread ID (if available)
|
| 559 |
+
%(threadName)s Thread name (if available)
|
| 560 |
+
%(process)d Process ID (if available)
|
| 561 |
+
%(message)s The result of record.getMessage(), computed just as
|
| 562 |
+
the record is emitted
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
converter = time.localtime
|
| 566 |
+
|
| 567 |
+
def __init__(self, fmt=None, datefmt=None, style='%', validate=True, *,
|
| 568 |
+
defaults=None):
|
| 569 |
+
"""
|
| 570 |
+
Initialize the formatter with specified format strings.
|
| 571 |
+
|
| 572 |
+
Initialize the formatter either with the specified format string, or a
|
| 573 |
+
default as described above. Allow for specialized date formatting with
|
| 574 |
+
the optional datefmt argument. If datefmt is omitted, you get an
|
| 575 |
+
ISO8601-like (or RFC 3339-like) format.
|
| 576 |
+
|
| 577 |
+
Use a style parameter of '%', '{' or '$' to specify that you want to
|
| 578 |
+
use one of %-formatting, :meth:`str.format` (``{}``) formatting or
|
| 579 |
+
:class:`string.Template` formatting in your format string.
|
| 580 |
+
|
| 581 |
+
.. versionchanged:: 3.2
|
| 582 |
+
Added the ``style`` parameter.
|
| 583 |
+
"""
|
| 584 |
+
if style not in _STYLES:
|
| 585 |
+
raise ValueError('Style must be one of: %s' % ','.join(
|
| 586 |
+
_STYLES.keys()))
|
| 587 |
+
self._style = _STYLES[style][0](fmt, defaults=defaults)
|
| 588 |
+
if validate:
|
| 589 |
+
self._style.validate()
|
| 590 |
+
|
| 591 |
+
self._fmt = self._style._fmt
|
| 592 |
+
self.datefmt = datefmt
|
| 593 |
+
|
| 594 |
+
default_time_format = '%Y-%m-%d %H:%M:%S'
|
| 595 |
+
default_msec_format = '%s,%03d'
|
| 596 |
+
|
| 597 |
+
def formatTime(self, record, datefmt=None):
|
| 598 |
+
"""
|
| 599 |
+
Return the creation time of the specified LogRecord as formatted text.
|
| 600 |
+
|
| 601 |
+
This method should be called from format() by a formatter which
|
| 602 |
+
wants to make use of a formatted time. This method can be overridden
|
| 603 |
+
in formatters to provide for any specific requirement, but the
|
| 604 |
+
basic behaviour is as follows: if datefmt (a string) is specified,
|
| 605 |
+
it is used with time.strftime() to format the creation time of the
|
| 606 |
+
record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used.
|
| 607 |
+
The resulting string is returned. This function uses a user-configurable
|
| 608 |
+
function to convert the creation time to a tuple. By default,
|
| 609 |
+
time.localtime() is used; to change this for a particular formatter
|
| 610 |
+
instance, set the 'converter' attribute to a function with the same
|
| 611 |
+
signature as time.localtime() or time.gmtime(). To change it for all
|
| 612 |
+
formatters, for example if you want all logging times to be shown in GMT,
|
| 613 |
+
set the 'converter' attribute in the Formatter class.
|
| 614 |
+
"""
|
| 615 |
+
ct = self.converter(record.created)
|
| 616 |
+
if datefmt:
|
| 617 |
+
s = time.strftime(datefmt, ct)
|
| 618 |
+
else:
|
| 619 |
+
s = time.strftime(self.default_time_format, ct)
|
| 620 |
+
if self.default_msec_format:
|
| 621 |
+
s = self.default_msec_format % (s, record.msecs)
|
| 622 |
+
return s
|
| 623 |
+
|
| 624 |
+
def formatException(self, ei):
|
| 625 |
+
"""
|
| 626 |
+
Format and return the specified exception information as a string.
|
| 627 |
+
|
| 628 |
+
This default implementation just uses
|
| 629 |
+
traceback.print_exception()
|
| 630 |
+
"""
|
| 631 |
+
sio = io.StringIO()
|
| 632 |
+
tb = ei[2]
|
| 633 |
+
# See issues #9427, #1553375. Commented out for now.
|
| 634 |
+
#if getattr(self, 'fullstack', False):
|
| 635 |
+
# traceback.print_stack(tb.tb_frame.f_back, file=sio)
|
| 636 |
+
traceback.print_exception(ei[0], ei[1], tb, None, sio)
|
| 637 |
+
s = sio.getvalue()
|
| 638 |
+
sio.close()
|
| 639 |
+
if s[-1:] == "\n":
|
| 640 |
+
s = s[:-1]
|
| 641 |
+
return s
|
| 642 |
+
|
| 643 |
+
def usesTime(self):
|
| 644 |
+
"""
|
| 645 |
+
Check if the format uses the creation time of the record.
|
| 646 |
+
"""
|
| 647 |
+
return self._style.usesTime()
|
| 648 |
+
|
| 649 |
+
def formatMessage(self, record):
|
| 650 |
+
return self._style.format(record)
|
| 651 |
+
|
| 652 |
+
def formatStack(self, stack_info):
|
| 653 |
+
"""
|
| 654 |
+
This method is provided as an extension point for specialized
|
| 655 |
+
formatting of stack information.
|
| 656 |
+
|
| 657 |
+
The input data is a string as returned from a call to
|
| 658 |
+
:func:`traceback.print_stack`, but with the last trailing newline
|
| 659 |
+
removed.
|
| 660 |
+
|
| 661 |
+
The base implementation just returns the value passed in.
|
| 662 |
+
"""
|
| 663 |
+
return stack_info
|
| 664 |
+
|
| 665 |
+
def format(self, record):
|
| 666 |
+
"""
|
| 667 |
+
Format the specified record as text.
|
| 668 |
+
|
| 669 |
+
The record's attribute dictionary is used as the operand to a
|
| 670 |
+
string formatting operation which yields the returned string.
|
| 671 |
+
Before formatting the dictionary, a couple of preparatory steps
|
| 672 |
+
are carried out. The message attribute of the record is computed
|
| 673 |
+
using LogRecord.getMessage(). If the formatting string uses the
|
| 674 |
+
time (as determined by a call to usesTime(), formatTime() is
|
| 675 |
+
called to format the event time. If there is exception information,
|
| 676 |
+
it is formatted using formatException() and appended to the message.
|
| 677 |
+
"""
|
| 678 |
+
record.message = record.getMessage()
|
| 679 |
+
if self.usesTime():
|
| 680 |
+
record.asctime = self.formatTime(record, self.datefmt)
|
| 681 |
+
s = self.formatMessage(record)
|
| 682 |
+
if record.exc_info:
|
| 683 |
+
# Cache the traceback text to avoid converting it multiple times
|
| 684 |
+
# (it's constant anyway)
|
| 685 |
+
if not record.exc_text:
|
| 686 |
+
record.exc_text = self.formatException(record.exc_info)
|
| 687 |
+
if record.exc_text:
|
| 688 |
+
if s[-1:] != "\n":
|
| 689 |
+
s = s + "\n"
|
| 690 |
+
s = s + record.exc_text
|
| 691 |
+
if record.stack_info:
|
| 692 |
+
if s[-1:] != "\n":
|
| 693 |
+
s = s + "\n"
|
| 694 |
+
s = s + self.formatStack(record.stack_info)
|
| 695 |
+
return s
|
| 696 |
+
|
| 697 |
+
#
|
| 698 |
+
# The default formatter to use when no other is specified
|
| 699 |
+
#
|
| 700 |
+
_defaultFormatter = Formatter()
|
| 701 |
+
|
| 702 |
+
class BufferingFormatter(object):
|
| 703 |
+
"""
|
| 704 |
+
A formatter suitable for formatting a number of records.
|
| 705 |
+
"""
|
| 706 |
+
def __init__(self, linefmt=None):
|
| 707 |
+
"""
|
| 708 |
+
Optionally specify a formatter which will be used to format each
|
| 709 |
+
individual record.
|
| 710 |
+
"""
|
| 711 |
+
if linefmt:
|
| 712 |
+
self.linefmt = linefmt
|
| 713 |
+
else:
|
| 714 |
+
self.linefmt = _defaultFormatter
|
| 715 |
+
|
| 716 |
+
def formatHeader(self, records):
|
| 717 |
+
"""
|
| 718 |
+
Return the header string for the specified records.
|
| 719 |
+
"""
|
| 720 |
+
return ""
|
| 721 |
+
|
| 722 |
+
def formatFooter(self, records):
|
| 723 |
+
"""
|
| 724 |
+
Return the footer string for the specified records.
|
| 725 |
+
"""
|
| 726 |
+
return ""
|
| 727 |
+
|
| 728 |
+
def format(self, records):
|
| 729 |
+
"""
|
| 730 |
+
Format the specified records and return the result as a string.
|
| 731 |
+
"""
|
| 732 |
+
rv = ""
|
| 733 |
+
if len(records) > 0:
|
| 734 |
+
rv = rv + self.formatHeader(records)
|
| 735 |
+
for record in records:
|
| 736 |
+
rv = rv + self.linefmt.format(record)
|
| 737 |
+
rv = rv + self.formatFooter(records)
|
| 738 |
+
return rv
|
| 739 |
+
|
| 740 |
+
#---------------------------------------------------------------------------
|
| 741 |
+
# Filter classes and functions
|
| 742 |
+
#---------------------------------------------------------------------------
|
| 743 |
+
|
| 744 |
+
class Filter(object):
|
| 745 |
+
"""
|
| 746 |
+
Filter instances are used to perform arbitrary filtering of LogRecords.
|
| 747 |
+
|
| 748 |
+
Loggers and Handlers can optionally use Filter instances to filter
|
| 749 |
+
records as desired. The base filter class only allows events which are
|
| 750 |
+
below a certain point in the logger hierarchy. For example, a filter
|
| 751 |
+
initialized with "A.B" will allow events logged by loggers "A.B",
|
| 752 |
+
"A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
|
| 753 |
+
initialized with the empty string, all events are passed.
|
| 754 |
+
"""
|
| 755 |
+
def __init__(self, name=''):
|
| 756 |
+
"""
|
| 757 |
+
Initialize a filter.
|
| 758 |
+
|
| 759 |
+
Initialize with the name of the logger which, together with its
|
| 760 |
+
children, will have its events allowed through the filter. If no
|
| 761 |
+
name is specified, allow every event.
|
| 762 |
+
"""
|
| 763 |
+
self.name = name
|
| 764 |
+
self.nlen = len(name)
|
| 765 |
+
|
| 766 |
+
def filter(self, record):
|
| 767 |
+
"""
|
| 768 |
+
Determine if the specified record is to be logged.
|
| 769 |
+
|
| 770 |
+
Returns True if the record should be logged, or False otherwise.
|
| 771 |
+
If deemed appropriate, the record may be modified in-place.
|
| 772 |
+
"""
|
| 773 |
+
if self.nlen == 0:
|
| 774 |
+
return True
|
| 775 |
+
elif self.name == record.name:
|
| 776 |
+
return True
|
| 777 |
+
elif record.name.find(self.name, 0, self.nlen) != 0:
|
| 778 |
+
return False
|
| 779 |
+
return (record.name[self.nlen] == ".")
|
| 780 |
+
|
| 781 |
+
class Filterer(object):
|
| 782 |
+
"""
|
| 783 |
+
A base class for loggers and handlers which allows them to share
|
| 784 |
+
common code.
|
| 785 |
+
"""
|
| 786 |
+
def __init__(self):
|
| 787 |
+
"""
|
| 788 |
+
Initialize the list of filters to be an empty list.
|
| 789 |
+
"""
|
| 790 |
+
self.filters = []
|
| 791 |
+
|
| 792 |
+
def addFilter(self, filter):
|
| 793 |
+
"""
|
| 794 |
+
Add the specified filter to this handler.
|
| 795 |
+
"""
|
| 796 |
+
if not (filter in self.filters):
|
| 797 |
+
self.filters.append(filter)
|
| 798 |
+
|
| 799 |
+
def removeFilter(self, filter):
|
| 800 |
+
"""
|
| 801 |
+
Remove the specified filter from this handler.
|
| 802 |
+
"""
|
| 803 |
+
if filter in self.filters:
|
| 804 |
+
self.filters.remove(filter)
|
| 805 |
+
|
| 806 |
+
def filter(self, record):
|
| 807 |
+
"""
|
| 808 |
+
Determine if a record is loggable by consulting all the filters.
|
| 809 |
+
|
| 810 |
+
The default is to allow the record to be logged; any filter can veto
|
| 811 |
+
this and the record is then dropped. Returns a zero value if a record
|
| 812 |
+
is to be dropped, else non-zero.
|
| 813 |
+
|
| 814 |
+
.. versionchanged:: 3.2
|
| 815 |
+
|
| 816 |
+
Allow filters to be just callables.
|
| 817 |
+
"""
|
| 818 |
+
rv = True
|
| 819 |
+
for f in self.filters:
|
| 820 |
+
if hasattr(f, 'filter'):
|
| 821 |
+
result = f.filter(record)
|
| 822 |
+
else:
|
| 823 |
+
result = f(record) # assume callable - will raise if not
|
| 824 |
+
if not result:
|
| 825 |
+
rv = False
|
| 826 |
+
break
|
| 827 |
+
return rv
|
| 828 |
+
|
| 829 |
+
#---------------------------------------------------------------------------
|
| 830 |
+
# Handler classes and functions
|
| 831 |
+
#---------------------------------------------------------------------------
|
| 832 |
+
|
| 833 |
+
_handlers = weakref.WeakValueDictionary() #map of handler names to handlers
|
| 834 |
+
_handlerList = [] # added to allow handlers to be removed in reverse of order initialized
|
| 835 |
+
|
| 836 |
+
def _removeHandlerRef(wr):
|
| 837 |
+
"""
|
| 838 |
+
Remove a handler reference from the internal cleanup list.
|
| 839 |
+
"""
|
| 840 |
+
# This function can be called during module teardown, when globals are
|
| 841 |
+
# set to None. It can also be called from another thread. So we need to
|
| 842 |
+
# pre-emptively grab the necessary globals and check if they're None,
|
| 843 |
+
# to prevent race conditions and failures during interpreter shutdown.
|
| 844 |
+
acquire, release, handlers = _acquireLock, _releaseLock, _handlerList
|
| 845 |
+
if acquire and release and handlers:
|
| 846 |
+
acquire()
|
| 847 |
+
try:
|
| 848 |
+
if wr in handlers:
|
| 849 |
+
handlers.remove(wr)
|
| 850 |
+
finally:
|
| 851 |
+
release()
|
| 852 |
+
|
| 853 |
+
def _addHandlerRef(handler):
|
| 854 |
+
"""
|
| 855 |
+
Add a handler to the internal cleanup list using a weak reference.
|
| 856 |
+
"""
|
| 857 |
+
_acquireLock()
|
| 858 |
+
try:
|
| 859 |
+
_handlerList.append(weakref.ref(handler, _removeHandlerRef))
|
| 860 |
+
finally:
|
| 861 |
+
_releaseLock()
|
| 862 |
+
|
| 863 |
+
class Handler(Filterer):
|
| 864 |
+
"""
|
| 865 |
+
Handler instances dispatch logging events to specific destinations.
|
| 866 |
+
|
| 867 |
+
The base handler class. Acts as a placeholder which defines the Handler
|
| 868 |
+
interface. Handlers can optionally use Formatter instances to format
|
| 869 |
+
records as desired. By default, no formatter is specified; in this case,
|
| 870 |
+
the 'raw' message as determined by record.message is logged.
|
| 871 |
+
"""
|
| 872 |
+
def __init__(self, level=NOTSET):
|
| 873 |
+
"""
|
| 874 |
+
Initializes the instance - basically setting the formatter to None
|
| 875 |
+
and the filter list to empty.
|
| 876 |
+
"""
|
| 877 |
+
Filterer.__init__(self)
|
| 878 |
+
self._name = None
|
| 879 |
+
self.level = _checkLevel(level)
|
| 880 |
+
self.formatter = None
|
| 881 |
+
self._closed = False
|
| 882 |
+
# Add the handler to the global _handlerList (for cleanup on shutdown)
|
| 883 |
+
_addHandlerRef(self)
|
| 884 |
+
self.createLock()
|
| 885 |
+
|
| 886 |
+
def get_name(self):
|
| 887 |
+
return self._name
|
| 888 |
+
|
| 889 |
+
def set_name(self, name):
|
| 890 |
+
_acquireLock()
|
| 891 |
+
try:
|
| 892 |
+
if self._name in _handlers:
|
| 893 |
+
del _handlers[self._name]
|
| 894 |
+
self._name = name
|
| 895 |
+
if name:
|
| 896 |
+
_handlers[name] = self
|
| 897 |
+
finally:
|
| 898 |
+
_releaseLock()
|
| 899 |
+
|
| 900 |
+
name = property(get_name, set_name)
|
| 901 |
+
|
| 902 |
+
def createLock(self):
|
| 903 |
+
"""
|
| 904 |
+
Acquire a thread lock for serializing access to the underlying I/O.
|
| 905 |
+
"""
|
| 906 |
+
self.lock = threading.RLock()
|
| 907 |
+
_register_at_fork_reinit_lock(self)
|
| 908 |
+
|
| 909 |
+
def _at_fork_reinit(self):
|
| 910 |
+
self.lock._at_fork_reinit()
|
| 911 |
+
|
| 912 |
+
def acquire(self):
|
| 913 |
+
"""
|
| 914 |
+
Acquire the I/O thread lock.
|
| 915 |
+
"""
|
| 916 |
+
if self.lock:
|
| 917 |
+
self.lock.acquire()
|
| 918 |
+
|
| 919 |
+
def release(self):
|
| 920 |
+
"""
|
| 921 |
+
Release the I/O thread lock.
|
| 922 |
+
"""
|
| 923 |
+
if self.lock:
|
| 924 |
+
self.lock.release()
|
| 925 |
+
|
| 926 |
+
def setLevel(self, level):
|
| 927 |
+
"""
|
| 928 |
+
Set the logging level of this handler. level must be an int or a str.
|
| 929 |
+
"""
|
| 930 |
+
self.level = _checkLevel(level)
|
| 931 |
+
|
| 932 |
+
def format(self, record):
|
| 933 |
+
"""
|
| 934 |
+
Format the specified record.
|
| 935 |
+
|
| 936 |
+
If a formatter is set, use it. Otherwise, use the default formatter
|
| 937 |
+
for the module.
|
| 938 |
+
"""
|
| 939 |
+
if self.formatter:
|
| 940 |
+
fmt = self.formatter
|
| 941 |
+
else:
|
| 942 |
+
fmt = _defaultFormatter
|
| 943 |
+
return fmt.format(record)
|
| 944 |
+
|
| 945 |
+
def emit(self, record):
|
| 946 |
+
"""
|
| 947 |
+
Do whatever it takes to actually log the specified logging record.
|
| 948 |
+
|
| 949 |
+
This version is intended to be implemented by subclasses and so
|
| 950 |
+
raises a NotImplementedError.
|
| 951 |
+
"""
|
| 952 |
+
raise NotImplementedError('emit must be implemented '
|
| 953 |
+
'by Handler subclasses')
|
| 954 |
+
|
| 955 |
+
def handle(self, record):
|
| 956 |
+
"""
|
| 957 |
+
Conditionally emit the specified logging record.
|
| 958 |
+
|
| 959 |
+
Emission depends on filters which may have been added to the handler.
|
| 960 |
+
Wrap the actual emission of the record with acquisition/release of
|
| 961 |
+
the I/O thread lock. Returns whether the filter passed the record for
|
| 962 |
+
emission.
|
| 963 |
+
"""
|
| 964 |
+
rv = self.filter(record)
|
| 965 |
+
if rv:
|
| 966 |
+
self.acquire()
|
| 967 |
+
try:
|
| 968 |
+
self.emit(record)
|
| 969 |
+
finally:
|
| 970 |
+
self.release()
|
| 971 |
+
return rv
|
| 972 |
+
|
| 973 |
+
def setFormatter(self, fmt):
|
| 974 |
+
"""
|
| 975 |
+
Set the formatter for this handler.
|
| 976 |
+
"""
|
| 977 |
+
self.formatter = fmt
|
| 978 |
+
|
| 979 |
+
def flush(self):
|
| 980 |
+
"""
|
| 981 |
+
Ensure all logging output has been flushed.
|
| 982 |
+
|
| 983 |
+
This version does nothing and is intended to be implemented by
|
| 984 |
+
subclasses.
|
| 985 |
+
"""
|
| 986 |
+
pass
|
| 987 |
+
|
| 988 |
+
def close(self):
|
| 989 |
+
"""
|
| 990 |
+
Tidy up any resources used by the handler.
|
| 991 |
+
|
| 992 |
+
This version removes the handler from an internal map of handlers,
|
| 993 |
+
_handlers, which is used for handler lookup by name. Subclasses
|
| 994 |
+
should ensure that this gets called from overridden close()
|
| 995 |
+
methods.
|
| 996 |
+
"""
|
| 997 |
+
#get the module data lock, as we're updating a shared structure.
|
| 998 |
+
_acquireLock()
|
| 999 |
+
try: #unlikely to raise an exception, but you never know...
|
| 1000 |
+
self._closed = True
|
| 1001 |
+
if self._name and self._name in _handlers:
|
| 1002 |
+
del _handlers[self._name]
|
| 1003 |
+
finally:
|
| 1004 |
+
_releaseLock()
|
| 1005 |
+
|
| 1006 |
+
def handleError(self, record):
|
| 1007 |
+
"""
|
| 1008 |
+
Handle errors which occur during an emit() call.
|
| 1009 |
+
|
| 1010 |
+
This method should be called from handlers when an exception is
|
| 1011 |
+
encountered during an emit() call. If raiseExceptions is false,
|
| 1012 |
+
exceptions get silently ignored. This is what is mostly wanted
|
| 1013 |
+
for a logging system - most users will not care about errors in
|
| 1014 |
+
the logging system, they are more interested in application errors.
|
| 1015 |
+
You could, however, replace this with a custom handler if you wish.
|
| 1016 |
+
The record which was being processed is passed in to this method.
|
| 1017 |
+
"""
|
| 1018 |
+
if raiseExceptions and sys.stderr: # see issue 13807
|
| 1019 |
+
t, v, tb = sys.exc_info()
|
| 1020 |
+
try:
|
| 1021 |
+
sys.stderr.write('--- Logging error ---\n')
|
| 1022 |
+
traceback.print_exception(t, v, tb, None, sys.stderr)
|
| 1023 |
+
sys.stderr.write('Call stack:\n')
|
| 1024 |
+
# Walk the stack frame up until we're out of logging,
|
| 1025 |
+
# so as to print the calling context.
|
| 1026 |
+
frame = tb.tb_frame
|
| 1027 |
+
while (frame and os.path.dirname(frame.f_code.co_filename) ==
|
| 1028 |
+
__path__[0]):
|
| 1029 |
+
frame = frame.f_back
|
| 1030 |
+
if frame:
|
| 1031 |
+
traceback.print_stack(frame, file=sys.stderr)
|
| 1032 |
+
else:
|
| 1033 |
+
# couldn't find the right stack frame, for some reason
|
| 1034 |
+
sys.stderr.write('Logged from file %s, line %s\n' % (
|
| 1035 |
+
record.filename, record.lineno))
|
| 1036 |
+
# Issue 18671: output logging message and arguments
|
| 1037 |
+
try:
|
| 1038 |
+
sys.stderr.write('Message: %r\n'
|
| 1039 |
+
'Arguments: %s\n' % (record.msg,
|
| 1040 |
+
record.args))
|
| 1041 |
+
except RecursionError: # See issue 36272
|
| 1042 |
+
raise
|
| 1043 |
+
except Exception:
|
| 1044 |
+
sys.stderr.write('Unable to print the message and arguments'
|
| 1045 |
+
' - possible formatting error.\nUse the'
|
| 1046 |
+
' traceback above to help find the error.\n'
|
| 1047 |
+
)
|
| 1048 |
+
except OSError: #pragma: no cover
|
| 1049 |
+
pass # see issue 5971
|
| 1050 |
+
finally:
|
| 1051 |
+
del t, v, tb
|
| 1052 |
+
|
| 1053 |
+
def __repr__(self):
|
| 1054 |
+
level = getLevelName(self.level)
|
| 1055 |
+
return '<%s (%s)>' % (self.__class__.__name__, level)
|
| 1056 |
+
|
| 1057 |
+
class StreamHandler(Handler):
|
| 1058 |
+
"""
|
| 1059 |
+
A handler class which writes logging records, appropriately formatted,
|
| 1060 |
+
to a stream. Note that this class does not close the stream, as
|
| 1061 |
+
sys.stdout or sys.stderr may be used.
|
| 1062 |
+
"""
|
| 1063 |
+
|
| 1064 |
+
terminator = '\n'
|
| 1065 |
+
|
| 1066 |
+
def __init__(self, stream=None):
|
| 1067 |
+
"""
|
| 1068 |
+
Initialize the handler.
|
| 1069 |
+
|
| 1070 |
+
If stream is not specified, sys.stderr is used.
|
| 1071 |
+
"""
|
| 1072 |
+
Handler.__init__(self)
|
| 1073 |
+
if stream is None:
|
| 1074 |
+
stream = sys.stderr
|
| 1075 |
+
self.stream = stream
|
| 1076 |
+
|
| 1077 |
+
def flush(self):
|
| 1078 |
+
"""
|
| 1079 |
+
Flushes the stream.
|
| 1080 |
+
"""
|
| 1081 |
+
self.acquire()
|
| 1082 |
+
try:
|
| 1083 |
+
if self.stream and hasattr(self.stream, "flush"):
|
| 1084 |
+
self.stream.flush()
|
| 1085 |
+
finally:
|
| 1086 |
+
self.release()
|
| 1087 |
+
|
| 1088 |
+
def emit(self, record):
|
| 1089 |
+
"""
|
| 1090 |
+
Emit a record.
|
| 1091 |
+
|
| 1092 |
+
If a formatter is specified, it is used to format the record.
|
| 1093 |
+
The record is then written to the stream with a trailing newline. If
|
| 1094 |
+
exception information is present, it is formatted using
|
| 1095 |
+
traceback.print_exception and appended to the stream. If the stream
|
| 1096 |
+
has an 'encoding' attribute, it is used to determine how to do the
|
| 1097 |
+
output to the stream.
|
| 1098 |
+
"""
|
| 1099 |
+
try:
|
| 1100 |
+
msg = self.format(record)
|
| 1101 |
+
stream = self.stream
|
| 1102 |
+
# issue 35046: merged two stream.writes into one.
|
| 1103 |
+
stream.write(msg + self.terminator)
|
| 1104 |
+
self.flush()
|
| 1105 |
+
except RecursionError: # See issue 36272
|
| 1106 |
+
raise
|
| 1107 |
+
except Exception:
|
| 1108 |
+
self.handleError(record)
|
| 1109 |
+
|
| 1110 |
+
def setStream(self, stream):
|
| 1111 |
+
"""
|
| 1112 |
+
Sets the StreamHandler's stream to the specified value,
|
| 1113 |
+
if it is different.
|
| 1114 |
+
|
| 1115 |
+
Returns the old stream, if the stream was changed, or None
|
| 1116 |
+
if it wasn't.
|
| 1117 |
+
"""
|
| 1118 |
+
if stream is self.stream:
|
| 1119 |
+
result = None
|
| 1120 |
+
else:
|
| 1121 |
+
result = self.stream
|
| 1122 |
+
self.acquire()
|
| 1123 |
+
try:
|
| 1124 |
+
self.flush()
|
| 1125 |
+
self.stream = stream
|
| 1126 |
+
finally:
|
| 1127 |
+
self.release()
|
| 1128 |
+
return result
|
| 1129 |
+
|
| 1130 |
+
def __repr__(self):
|
| 1131 |
+
level = getLevelName(self.level)
|
| 1132 |
+
name = getattr(self.stream, 'name', '')
|
| 1133 |
+
# bpo-36015: name can be an int
|
| 1134 |
+
name = str(name)
|
| 1135 |
+
if name:
|
| 1136 |
+
name += ' '
|
| 1137 |
+
return '<%s %s(%s)>' % (self.__class__.__name__, name, level)
|
| 1138 |
+
|
| 1139 |
+
|
| 1140 |
+
class FileHandler(StreamHandler):
|
| 1141 |
+
"""
|
| 1142 |
+
A handler class which writes formatted logging records to disk files.
|
| 1143 |
+
"""
|
| 1144 |
+
def __init__(self, filename, mode='a', encoding=None, delay=False, errors=None):
|
| 1145 |
+
"""
|
| 1146 |
+
Open the specified file and use it as the stream for logging.
|
| 1147 |
+
"""
|
| 1148 |
+
# Issue #27493: add support for Path objects to be passed in
|
| 1149 |
+
filename = os.fspath(filename)
|
| 1150 |
+
#keep the absolute path, otherwise derived classes which use this
|
| 1151 |
+
#may come a cropper when the current directory changes
|
| 1152 |
+
self.baseFilename = os.path.abspath(filename)
|
| 1153 |
+
self.mode = mode
|
| 1154 |
+
self.encoding = encoding
|
| 1155 |
+
if "b" not in mode:
|
| 1156 |
+
self.encoding = io.text_encoding(encoding)
|
| 1157 |
+
self.errors = errors
|
| 1158 |
+
self.delay = delay
|
| 1159 |
+
# bpo-26789: FileHandler keeps a reference to the builtin open()
|
| 1160 |
+
# function to be able to open or reopen the file during Python
|
| 1161 |
+
# finalization.
|
| 1162 |
+
self._builtin_open = open
|
| 1163 |
+
if delay:
|
| 1164 |
+
#We don't open the stream, but we still need to call the
|
| 1165 |
+
#Handler constructor to set level, formatter, lock etc.
|
| 1166 |
+
Handler.__init__(self)
|
| 1167 |
+
self.stream = None
|
| 1168 |
+
else:
|
| 1169 |
+
StreamHandler.__init__(self, self._open())
|
| 1170 |
+
|
| 1171 |
+
def close(self):
|
| 1172 |
+
"""
|
| 1173 |
+
Closes the stream.
|
| 1174 |
+
"""
|
| 1175 |
+
self.acquire()
|
| 1176 |
+
try:
|
| 1177 |
+
try:
|
| 1178 |
+
if self.stream:
|
| 1179 |
+
try:
|
| 1180 |
+
self.flush()
|
| 1181 |
+
finally:
|
| 1182 |
+
stream = self.stream
|
| 1183 |
+
self.stream = None
|
| 1184 |
+
if hasattr(stream, "close"):
|
| 1185 |
+
stream.close()
|
| 1186 |
+
finally:
|
| 1187 |
+
# Issue #19523: call unconditionally to
|
| 1188 |
+
# prevent a handler leak when delay is set
|
| 1189 |
+
# Also see Issue #42378: we also rely on
|
| 1190 |
+
# self._closed being set to True there
|
| 1191 |
+
StreamHandler.close(self)
|
| 1192 |
+
finally:
|
| 1193 |
+
self.release()
|
| 1194 |
+
|
| 1195 |
+
def _open(self):
|
| 1196 |
+
"""
|
| 1197 |
+
Open the current base file with the (original) mode and encoding.
|
| 1198 |
+
Return the resulting stream.
|
| 1199 |
+
"""
|
| 1200 |
+
open_func = self._builtin_open
|
| 1201 |
+
return open_func(self.baseFilename, self.mode,
|
| 1202 |
+
encoding=self.encoding, errors=self.errors)
|
| 1203 |
+
|
| 1204 |
+
def emit(self, record):
|
| 1205 |
+
"""
|
| 1206 |
+
Emit a record.
|
| 1207 |
+
|
| 1208 |
+
If the stream was not opened because 'delay' was specified in the
|
| 1209 |
+
constructor, open it before calling the superclass's emit.
|
| 1210 |
+
|
| 1211 |
+
If stream is not open, current mode is 'w' and `_closed=True`, record
|
| 1212 |
+
will not be emitted (see Issue #42378).
|
| 1213 |
+
"""
|
| 1214 |
+
if self.stream is None:
|
| 1215 |
+
if self.mode != 'w' or not self._closed:
|
| 1216 |
+
self.stream = self._open()
|
| 1217 |
+
if self.stream:
|
| 1218 |
+
StreamHandler.emit(self, record)
|
| 1219 |
+
|
| 1220 |
+
def __repr__(self):
|
| 1221 |
+
level = getLevelName(self.level)
|
| 1222 |
+
return '<%s %s (%s)>' % (self.__class__.__name__, self.baseFilename, level)
|
| 1223 |
+
|
| 1224 |
+
|
| 1225 |
+
class _StderrHandler(StreamHandler):
|
| 1226 |
+
"""
|
| 1227 |
+
This class is like a StreamHandler using sys.stderr, but always uses
|
| 1228 |
+
whatever sys.stderr is currently set to rather than the value of
|
| 1229 |
+
sys.stderr at handler construction time.
|
| 1230 |
+
"""
|
| 1231 |
+
def __init__(self, level=NOTSET):
|
| 1232 |
+
"""
|
| 1233 |
+
Initialize the handler.
|
| 1234 |
+
"""
|
| 1235 |
+
Handler.__init__(self, level)
|
| 1236 |
+
|
| 1237 |
+
@property
|
| 1238 |
+
def stream(self):
|
| 1239 |
+
return sys.stderr
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
_defaultLastResort = _StderrHandler(WARNING)
|
| 1243 |
+
lastResort = _defaultLastResort
|
| 1244 |
+
|
| 1245 |
+
#---------------------------------------------------------------------------
|
| 1246 |
+
# Manager classes and functions
|
| 1247 |
+
#---------------------------------------------------------------------------
|
| 1248 |
+
|
| 1249 |
+
class PlaceHolder(object):
|
| 1250 |
+
"""
|
| 1251 |
+
PlaceHolder instances are used in the Manager logger hierarchy to take
|
| 1252 |
+
the place of nodes for which no loggers have been defined. This class is
|
| 1253 |
+
intended for internal use only and not as part of the public API.
|
| 1254 |
+
"""
|
| 1255 |
+
def __init__(self, alogger):
|
| 1256 |
+
"""
|
| 1257 |
+
Initialize with the specified logger being a child of this placeholder.
|
| 1258 |
+
"""
|
| 1259 |
+
self.loggerMap = { alogger : None }
|
| 1260 |
+
|
| 1261 |
+
def append(self, alogger):
|
| 1262 |
+
"""
|
| 1263 |
+
Add the specified logger as a child of this placeholder.
|
| 1264 |
+
"""
|
| 1265 |
+
if alogger not in self.loggerMap:
|
| 1266 |
+
self.loggerMap[alogger] = None
|
| 1267 |
+
|
| 1268 |
+
#
|
| 1269 |
+
# Determine which class to use when instantiating loggers.
|
| 1270 |
+
#
|
| 1271 |
+
|
| 1272 |
+
def setLoggerClass(klass):
|
| 1273 |
+
"""
|
| 1274 |
+
Set the class to be used when instantiating a logger. The class should
|
| 1275 |
+
define __init__() such that only a name argument is required, and the
|
| 1276 |
+
__init__() should call Logger.__init__()
|
| 1277 |
+
"""
|
| 1278 |
+
if klass != Logger:
|
| 1279 |
+
if not issubclass(klass, Logger):
|
| 1280 |
+
raise TypeError("logger not derived from logging.Logger: "
|
| 1281 |
+
+ klass.__name__)
|
| 1282 |
+
global _loggerClass
|
| 1283 |
+
_loggerClass = klass
|
| 1284 |
+
|
| 1285 |
+
def getLoggerClass():
|
| 1286 |
+
"""
|
| 1287 |
+
Return the class to be used when instantiating a logger.
|
| 1288 |
+
"""
|
| 1289 |
+
return _loggerClass
|
| 1290 |
+
|
| 1291 |
+
class Manager(object):
|
| 1292 |
+
"""
|
| 1293 |
+
There is [under normal circumstances] just one Manager instance, which
|
| 1294 |
+
holds the hierarchy of loggers.
|
| 1295 |
+
"""
|
| 1296 |
+
def __init__(self, rootnode):
|
| 1297 |
+
"""
|
| 1298 |
+
Initialize the manager with the root node of the logger hierarchy.
|
| 1299 |
+
"""
|
| 1300 |
+
self.root = rootnode
|
| 1301 |
+
self.disable = 0
|
| 1302 |
+
self.emittedNoHandlerWarning = False
|
| 1303 |
+
self.loggerDict = {}
|
| 1304 |
+
self.loggerClass = None
|
| 1305 |
+
self.logRecordFactory = None
|
| 1306 |
+
|
| 1307 |
+
@property
|
| 1308 |
+
def disable(self):
|
| 1309 |
+
return self._disable
|
| 1310 |
+
|
| 1311 |
+
@disable.setter
|
| 1312 |
+
def disable(self, value):
|
| 1313 |
+
self._disable = _checkLevel(value)
|
| 1314 |
+
|
| 1315 |
+
def getLogger(self, name):
|
| 1316 |
+
"""
|
| 1317 |
+
Get a logger with the specified name (channel name), creating it
|
| 1318 |
+
if it doesn't yet exist. This name is a dot-separated hierarchical
|
| 1319 |
+
name, such as "a", "a.b", "a.b.c" or similar.
|
| 1320 |
+
|
| 1321 |
+
If a PlaceHolder existed for the specified name [i.e. the logger
|
| 1322 |
+
didn't exist but a child of it did], replace it with the created
|
| 1323 |
+
logger and fix up the parent/child references which pointed to the
|
| 1324 |
+
placeholder to now point to the logger.
|
| 1325 |
+
"""
|
| 1326 |
+
rv = None
|
| 1327 |
+
if not isinstance(name, str):
|
| 1328 |
+
raise TypeError('A logger name must be a string')
|
| 1329 |
+
_acquireLock()
|
| 1330 |
+
try:
|
| 1331 |
+
if name in self.loggerDict:
|
| 1332 |
+
rv = self.loggerDict[name]
|
| 1333 |
+
if isinstance(rv, PlaceHolder):
|
| 1334 |
+
ph = rv
|
| 1335 |
+
rv = (self.loggerClass or _loggerClass)(name)
|
| 1336 |
+
rv.manager = self
|
| 1337 |
+
self.loggerDict[name] = rv
|
| 1338 |
+
self._fixupChildren(ph, rv)
|
| 1339 |
+
self._fixupParents(rv)
|
| 1340 |
+
else:
|
| 1341 |
+
rv = (self.loggerClass or _loggerClass)(name)
|
| 1342 |
+
rv.manager = self
|
| 1343 |
+
self.loggerDict[name] = rv
|
| 1344 |
+
self._fixupParents(rv)
|
| 1345 |
+
finally:
|
| 1346 |
+
_releaseLock()
|
| 1347 |
+
return rv
|
| 1348 |
+
|
| 1349 |
+
def setLoggerClass(self, klass):
|
| 1350 |
+
"""
|
| 1351 |
+
Set the class to be used when instantiating a logger with this Manager.
|
| 1352 |
+
"""
|
| 1353 |
+
if klass != Logger:
|
| 1354 |
+
if not issubclass(klass, Logger):
|
| 1355 |
+
raise TypeError("logger not derived from logging.Logger: "
|
| 1356 |
+
+ klass.__name__)
|
| 1357 |
+
self.loggerClass = klass
|
| 1358 |
+
|
| 1359 |
+
def setLogRecordFactory(self, factory):
|
| 1360 |
+
"""
|
| 1361 |
+
Set the factory to be used when instantiating a log record with this
|
| 1362 |
+
Manager.
|
| 1363 |
+
"""
|
| 1364 |
+
self.logRecordFactory = factory
|
| 1365 |
+
|
| 1366 |
+
def _fixupParents(self, alogger):
|
| 1367 |
+
"""
|
| 1368 |
+
Ensure that there are either loggers or placeholders all the way
|
| 1369 |
+
from the specified logger to the root of the logger hierarchy.
|
| 1370 |
+
"""
|
| 1371 |
+
name = alogger.name
|
| 1372 |
+
i = name.rfind(".")
|
| 1373 |
+
rv = None
|
| 1374 |
+
while (i > 0) and not rv:
|
| 1375 |
+
substr = name[:i]
|
| 1376 |
+
if substr not in self.loggerDict:
|
| 1377 |
+
self.loggerDict[substr] = PlaceHolder(alogger)
|
| 1378 |
+
else:
|
| 1379 |
+
obj = self.loggerDict[substr]
|
| 1380 |
+
if isinstance(obj, Logger):
|
| 1381 |
+
rv = obj
|
| 1382 |
+
else:
|
| 1383 |
+
assert isinstance(obj, PlaceHolder)
|
| 1384 |
+
obj.append(alogger)
|
| 1385 |
+
i = name.rfind(".", 0, i - 1)
|
| 1386 |
+
if not rv:
|
| 1387 |
+
rv = self.root
|
| 1388 |
+
alogger.parent = rv
|
| 1389 |
+
|
| 1390 |
+
def _fixupChildren(self, ph, alogger):
|
| 1391 |
+
"""
|
| 1392 |
+
Ensure that children of the placeholder ph are connected to the
|
| 1393 |
+
specified logger.
|
| 1394 |
+
"""
|
| 1395 |
+
name = alogger.name
|
| 1396 |
+
namelen = len(name)
|
| 1397 |
+
for c in ph.loggerMap.keys():
|
| 1398 |
+
#The if means ... if not c.parent.name.startswith(nm)
|
| 1399 |
+
if c.parent.name[:namelen] != name:
|
| 1400 |
+
alogger.parent = c.parent
|
| 1401 |
+
c.parent = alogger
|
| 1402 |
+
|
| 1403 |
+
def _clear_cache(self):
|
| 1404 |
+
"""
|
| 1405 |
+
Clear the cache for all loggers in loggerDict
|
| 1406 |
+
Called when level changes are made
|
| 1407 |
+
"""
|
| 1408 |
+
|
| 1409 |
+
_acquireLock()
|
| 1410 |
+
for logger in self.loggerDict.values():
|
| 1411 |
+
if isinstance(logger, Logger):
|
| 1412 |
+
logger._cache.clear()
|
| 1413 |
+
self.root._cache.clear()
|
| 1414 |
+
_releaseLock()
|
| 1415 |
+
|
| 1416 |
+
#---------------------------------------------------------------------------
|
| 1417 |
+
# Logger classes and functions
|
| 1418 |
+
#---------------------------------------------------------------------------
|
| 1419 |
+
|
| 1420 |
+
class Logger(Filterer):
|
| 1421 |
+
"""
|
| 1422 |
+
Instances of the Logger class represent a single logging channel. A
|
| 1423 |
+
"logging channel" indicates an area of an application. Exactly how an
|
| 1424 |
+
"area" is defined is up to the application developer. Since an
|
| 1425 |
+
application can have any number of areas, logging channels are identified
|
| 1426 |
+
by a unique string. Application areas can be nested (e.g. an area
|
| 1427 |
+
of "input processing" might include sub-areas "read CSV files", "read
|
| 1428 |
+
XLS files" and "read Gnumeric files"). To cater for this natural nesting,
|
| 1429 |
+
channel names are organized into a namespace hierarchy where levels are
|
| 1430 |
+
separated by periods, much like the Java or Python package namespace. So
|
| 1431 |
+
in the instance given above, channel names might be "input" for the upper
|
| 1432 |
+
level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
|
| 1433 |
+
There is no arbitrary limit to the depth of nesting.
|
| 1434 |
+
"""
|
| 1435 |
+
def __init__(self, name, level=NOTSET):
|
| 1436 |
+
"""
|
| 1437 |
+
Initialize the logger with a name and an optional level.
|
| 1438 |
+
"""
|
| 1439 |
+
Filterer.__init__(self)
|
| 1440 |
+
self.name = name
|
| 1441 |
+
self.level = _checkLevel(level)
|
| 1442 |
+
self.parent = None
|
| 1443 |
+
self.propagate = True
|
| 1444 |
+
self.handlers = []
|
| 1445 |
+
self.disabled = False
|
| 1446 |
+
self._cache = {}
|
| 1447 |
+
|
| 1448 |
+
def setLevel(self, level):
|
| 1449 |
+
"""
|
| 1450 |
+
Set the logging level of this logger. level must be an int or a str.
|
| 1451 |
+
"""
|
| 1452 |
+
self.level = _checkLevel(level)
|
| 1453 |
+
self.manager._clear_cache()
|
| 1454 |
+
|
| 1455 |
+
def debug(self, msg, *args, **kwargs):
|
| 1456 |
+
"""
|
| 1457 |
+
Log 'msg % args' with severity 'DEBUG'.
|
| 1458 |
+
|
| 1459 |
+
To pass exception information, use the keyword argument exc_info with
|
| 1460 |
+
a true value, e.g.
|
| 1461 |
+
|
| 1462 |
+
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
|
| 1463 |
+
"""
|
| 1464 |
+
if self.isEnabledFor(DEBUG):
|
| 1465 |
+
self._log(DEBUG, msg, args, **kwargs)
|
| 1466 |
+
|
| 1467 |
+
def info(self, msg, *args, **kwargs):
|
| 1468 |
+
"""
|
| 1469 |
+
Log 'msg % args' with severity 'INFO'.
|
| 1470 |
+
|
| 1471 |
+
To pass exception information, use the keyword argument exc_info with
|
| 1472 |
+
a true value, e.g.
|
| 1473 |
+
|
| 1474 |
+
logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
|
| 1475 |
+
"""
|
| 1476 |
+
if self.isEnabledFor(INFO):
|
| 1477 |
+
self._log(INFO, msg, args, **kwargs)
|
| 1478 |
+
|
| 1479 |
+
def warning(self, msg, *args, **kwargs):
|
| 1480 |
+
"""
|
| 1481 |
+
Log 'msg % args' with severity 'WARNING'.
|
| 1482 |
+
|
| 1483 |
+
To pass exception information, use the keyword argument exc_info with
|
| 1484 |
+
a true value, e.g.
|
| 1485 |
+
|
| 1486 |
+
logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
|
| 1487 |
+
"""
|
| 1488 |
+
if self.isEnabledFor(WARNING):
|
| 1489 |
+
self._log(WARNING, msg, args, **kwargs)
|
| 1490 |
+
|
| 1491 |
+
def warn(self, msg, *args, **kwargs):
|
| 1492 |
+
warnings.warn("The 'warn' method is deprecated, "
|
| 1493 |
+
"use 'warning' instead", DeprecationWarning, 2)
|
| 1494 |
+
self.warning(msg, *args, **kwargs)
|
| 1495 |
+
|
| 1496 |
+
def error(self, msg, *args, **kwargs):
|
| 1497 |
+
"""
|
| 1498 |
+
Log 'msg % args' with severity 'ERROR'.
|
| 1499 |
+
|
| 1500 |
+
To pass exception information, use the keyword argument exc_info with
|
| 1501 |
+
a true value, e.g.
|
| 1502 |
+
|
| 1503 |
+
logger.error("Houston, we have a %s", "major problem", exc_info=1)
|
| 1504 |
+
"""
|
| 1505 |
+
if self.isEnabledFor(ERROR):
|
| 1506 |
+
self._log(ERROR, msg, args, **kwargs)
|
| 1507 |
+
|
| 1508 |
+
def exception(self, msg, *args, exc_info=True, **kwargs):
|
| 1509 |
+
"""
|
| 1510 |
+
Convenience method for logging an ERROR with exception information.
|
| 1511 |
+
"""
|
| 1512 |
+
self.error(msg, *args, exc_info=exc_info, **kwargs)
|
| 1513 |
+
|
| 1514 |
+
def critical(self, msg, *args, **kwargs):
|
| 1515 |
+
"""
|
| 1516 |
+
Log 'msg % args' with severity 'CRITICAL'.
|
| 1517 |
+
|
| 1518 |
+
To pass exception information, use the keyword argument exc_info with
|
| 1519 |
+
a true value, e.g.
|
| 1520 |
+
|
| 1521 |
+
logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
|
| 1522 |
+
"""
|
| 1523 |
+
if self.isEnabledFor(CRITICAL):
|
| 1524 |
+
self._log(CRITICAL, msg, args, **kwargs)
|
| 1525 |
+
|
| 1526 |
+
def fatal(self, msg, *args, **kwargs):
|
| 1527 |
+
"""
|
| 1528 |
+
Don't use this method, use critical() instead.
|
| 1529 |
+
"""
|
| 1530 |
+
self.critical(msg, *args, **kwargs)
|
| 1531 |
+
|
| 1532 |
+
def log(self, level, msg, *args, **kwargs):
|
| 1533 |
+
"""
|
| 1534 |
+
Log 'msg % args' with the integer severity 'level'.
|
| 1535 |
+
|
| 1536 |
+
To pass exception information, use the keyword argument exc_info with
|
| 1537 |
+
a true value, e.g.
|
| 1538 |
+
|
| 1539 |
+
logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
|
| 1540 |
+
"""
|
| 1541 |
+
if not isinstance(level, int):
|
| 1542 |
+
if raiseExceptions:
|
| 1543 |
+
raise TypeError("level must be an integer")
|
| 1544 |
+
else:
|
| 1545 |
+
return
|
| 1546 |
+
if self.isEnabledFor(level):
|
| 1547 |
+
self._log(level, msg, args, **kwargs)
|
| 1548 |
+
|
| 1549 |
+
def findCaller(self, stack_info=False, stacklevel=1):
|
| 1550 |
+
"""
|
| 1551 |
+
Find the stack frame of the caller so that we can note the source
|
| 1552 |
+
file name, line number and function name.
|
| 1553 |
+
"""
|
| 1554 |
+
f = currentframe()
|
| 1555 |
+
#On some versions of IronPython, currentframe() returns None if
|
| 1556 |
+
#IronPython isn't run with -X:Frames.
|
| 1557 |
+
if f is not None:
|
| 1558 |
+
f = f.f_back
|
| 1559 |
+
orig_f = f
|
| 1560 |
+
while f and stacklevel > 1:
|
| 1561 |
+
f = f.f_back
|
| 1562 |
+
stacklevel -= 1
|
| 1563 |
+
if not f:
|
| 1564 |
+
f = orig_f
|
| 1565 |
+
rv = "(unknown file)", 0, "(unknown function)", None
|
| 1566 |
+
while hasattr(f, "f_code"):
|
| 1567 |
+
co = f.f_code
|
| 1568 |
+
filename = os.path.normcase(co.co_filename)
|
| 1569 |
+
if filename == _srcfile:
|
| 1570 |
+
f = f.f_back
|
| 1571 |
+
continue
|
| 1572 |
+
sinfo = None
|
| 1573 |
+
if stack_info:
|
| 1574 |
+
sio = io.StringIO()
|
| 1575 |
+
sio.write('Stack (most recent call last):\n')
|
| 1576 |
+
traceback.print_stack(f, file=sio)
|
| 1577 |
+
sinfo = sio.getvalue()
|
| 1578 |
+
if sinfo[-1] == '\n':
|
| 1579 |
+
sinfo = sinfo[:-1]
|
| 1580 |
+
sio.close()
|
| 1581 |
+
rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
|
| 1582 |
+
break
|
| 1583 |
+
return rv
|
| 1584 |
+
|
| 1585 |
+
def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
|
| 1586 |
+
func=None, extra=None, sinfo=None):
|
| 1587 |
+
"""
|
| 1588 |
+
A factory method which can be overridden in subclasses to create
|
| 1589 |
+
specialized LogRecords.
|
| 1590 |
+
"""
|
| 1591 |
+
rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
|
| 1592 |
+
sinfo)
|
| 1593 |
+
if extra is not None:
|
| 1594 |
+
for key in extra:
|
| 1595 |
+
if (key in ["message", "asctime"]) or (key in rv.__dict__):
|
| 1596 |
+
raise KeyError("Attempt to overwrite %r in LogRecord" % key)
|
| 1597 |
+
rv.__dict__[key] = extra[key]
|
| 1598 |
+
return rv
|
| 1599 |
+
|
| 1600 |
+
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False,
|
| 1601 |
+
stacklevel=1):
|
| 1602 |
+
"""
|
| 1603 |
+
Low-level logging routine which creates a LogRecord and then calls
|
| 1604 |
+
all the handlers of this logger to handle the record.
|
| 1605 |
+
"""
|
| 1606 |
+
sinfo = None
|
| 1607 |
+
if _srcfile:
|
| 1608 |
+
#IronPython doesn't track Python frames, so findCaller raises an
|
| 1609 |
+
#exception on some versions of IronPython. We trap it here so that
|
| 1610 |
+
#IronPython can use logging.
|
| 1611 |
+
try:
|
| 1612 |
+
fn, lno, func, sinfo = self.findCaller(stack_info, stacklevel)
|
| 1613 |
+
except ValueError: # pragma: no cover
|
| 1614 |
+
fn, lno, func = "(unknown file)", 0, "(unknown function)"
|
| 1615 |
+
else: # pragma: no cover
|
| 1616 |
+
fn, lno, func = "(unknown file)", 0, "(unknown function)"
|
| 1617 |
+
if exc_info:
|
| 1618 |
+
if isinstance(exc_info, BaseException):
|
| 1619 |
+
exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
|
| 1620 |
+
elif not isinstance(exc_info, tuple):
|
| 1621 |
+
exc_info = sys.exc_info()
|
| 1622 |
+
record = self.makeRecord(self.name, level, fn, lno, msg, args,
|
| 1623 |
+
exc_info, func, extra, sinfo)
|
| 1624 |
+
self.handle(record)
|
| 1625 |
+
|
| 1626 |
+
def handle(self, record):
|
| 1627 |
+
"""
|
| 1628 |
+
Call the handlers for the specified record.
|
| 1629 |
+
|
| 1630 |
+
This method is used for unpickled records received from a socket, as
|
| 1631 |
+
well as those created locally. Logger-level filtering is applied.
|
| 1632 |
+
"""
|
| 1633 |
+
if (not self.disabled) and self.filter(record):
|
| 1634 |
+
self.callHandlers(record)
|
| 1635 |
+
|
| 1636 |
+
def addHandler(self, hdlr):
|
| 1637 |
+
"""
|
| 1638 |
+
Add the specified handler to this logger.
|
| 1639 |
+
"""
|
| 1640 |
+
_acquireLock()
|
| 1641 |
+
try:
|
| 1642 |
+
if not (hdlr in self.handlers):
|
| 1643 |
+
self.handlers.append(hdlr)
|
| 1644 |
+
finally:
|
| 1645 |
+
_releaseLock()
|
| 1646 |
+
|
| 1647 |
+
def removeHandler(self, hdlr):
|
| 1648 |
+
"""
|
| 1649 |
+
Remove the specified handler from this logger.
|
| 1650 |
+
"""
|
| 1651 |
+
_acquireLock()
|
| 1652 |
+
try:
|
| 1653 |
+
if hdlr in self.handlers:
|
| 1654 |
+
self.handlers.remove(hdlr)
|
| 1655 |
+
finally:
|
| 1656 |
+
_releaseLock()
|
| 1657 |
+
|
| 1658 |
+
def hasHandlers(self):
|
| 1659 |
+
"""
|
| 1660 |
+
See if this logger has any handlers configured.
|
| 1661 |
+
|
| 1662 |
+
Loop through all handlers for this logger and its parents in the
|
| 1663 |
+
logger hierarchy. Return True if a handler was found, else False.
|
| 1664 |
+
Stop searching up the hierarchy whenever a logger with the "propagate"
|
| 1665 |
+
attribute set to zero is found - that will be the last logger which
|
| 1666 |
+
is checked for the existence of handlers.
|
| 1667 |
+
"""
|
| 1668 |
+
c = self
|
| 1669 |
+
rv = False
|
| 1670 |
+
while c:
|
| 1671 |
+
if c.handlers:
|
| 1672 |
+
rv = True
|
| 1673 |
+
break
|
| 1674 |
+
if not c.propagate:
|
| 1675 |
+
break
|
| 1676 |
+
else:
|
| 1677 |
+
c = c.parent
|
| 1678 |
+
return rv
|
| 1679 |
+
|
| 1680 |
+
def callHandlers(self, record):
|
| 1681 |
+
"""
|
| 1682 |
+
Pass a record to all relevant handlers.
|
| 1683 |
+
|
| 1684 |
+
Loop through all handlers for this logger and its parents in the
|
| 1685 |
+
logger hierarchy. If no handler was found, output a one-off error
|
| 1686 |
+
message to sys.stderr. Stop searching up the hierarchy whenever a
|
| 1687 |
+
logger with the "propagate" attribute set to zero is found - that
|
| 1688 |
+
will be the last logger whose handlers are called.
|
| 1689 |
+
"""
|
| 1690 |
+
c = self
|
| 1691 |
+
found = 0
|
| 1692 |
+
while c:
|
| 1693 |
+
for hdlr in c.handlers:
|
| 1694 |
+
found = found + 1
|
| 1695 |
+
if record.levelno >= hdlr.level:
|
| 1696 |
+
hdlr.handle(record)
|
| 1697 |
+
if not c.propagate:
|
| 1698 |
+
c = None #break out
|
| 1699 |
+
else:
|
| 1700 |
+
c = c.parent
|
| 1701 |
+
if (found == 0):
|
| 1702 |
+
if lastResort:
|
| 1703 |
+
if record.levelno >= lastResort.level:
|
| 1704 |
+
lastResort.handle(record)
|
| 1705 |
+
elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
|
| 1706 |
+
sys.stderr.write("No handlers could be found for logger"
|
| 1707 |
+
" \"%s\"\n" % self.name)
|
| 1708 |
+
self.manager.emittedNoHandlerWarning = True
|
| 1709 |
+
|
| 1710 |
+
def getEffectiveLevel(self):
|
| 1711 |
+
"""
|
| 1712 |
+
Get the effective level for this logger.
|
| 1713 |
+
|
| 1714 |
+
Loop through this logger and its parents in the logger hierarchy,
|
| 1715 |
+
looking for a non-zero logging level. Return the first one found.
|
| 1716 |
+
"""
|
| 1717 |
+
logger = self
|
| 1718 |
+
while logger:
|
| 1719 |
+
if logger.level:
|
| 1720 |
+
return logger.level
|
| 1721 |
+
logger = logger.parent
|
| 1722 |
+
return NOTSET
|
| 1723 |
+
|
| 1724 |
+
def isEnabledFor(self, level):
|
| 1725 |
+
"""
|
| 1726 |
+
Is this logger enabled for level 'level'?
|
| 1727 |
+
"""
|
| 1728 |
+
if self.disabled:
|
| 1729 |
+
return False
|
| 1730 |
+
|
| 1731 |
+
try:
|
| 1732 |
+
return self._cache[level]
|
| 1733 |
+
except KeyError:
|
| 1734 |
+
_acquireLock()
|
| 1735 |
+
try:
|
| 1736 |
+
if self.manager.disable >= level:
|
| 1737 |
+
is_enabled = self._cache[level] = False
|
| 1738 |
+
else:
|
| 1739 |
+
is_enabled = self._cache[level] = (
|
| 1740 |
+
level >= self.getEffectiveLevel()
|
| 1741 |
+
)
|
| 1742 |
+
finally:
|
| 1743 |
+
_releaseLock()
|
| 1744 |
+
return is_enabled
|
| 1745 |
+
|
| 1746 |
+
def getChild(self, suffix):
|
| 1747 |
+
"""
|
| 1748 |
+
Get a logger which is a descendant to this one.
|
| 1749 |
+
|
| 1750 |
+
This is a convenience method, such that
|
| 1751 |
+
|
| 1752 |
+
logging.getLogger('abc').getChild('def.ghi')
|
| 1753 |
+
|
| 1754 |
+
is the same as
|
| 1755 |
+
|
| 1756 |
+
logging.getLogger('abc.def.ghi')
|
| 1757 |
+
|
| 1758 |
+
It's useful, for example, when the parent logger is named using
|
| 1759 |
+
__name__ rather than a literal string.
|
| 1760 |
+
"""
|
| 1761 |
+
if self.root is not self:
|
| 1762 |
+
suffix = '.'.join((self.name, suffix))
|
| 1763 |
+
return self.manager.getLogger(suffix)
|
| 1764 |
+
|
| 1765 |
+
def __repr__(self):
|
| 1766 |
+
level = getLevelName(self.getEffectiveLevel())
|
| 1767 |
+
return '<%s %s (%s)>' % (self.__class__.__name__, self.name, level)
|
| 1768 |
+
|
| 1769 |
+
def __reduce__(self):
|
| 1770 |
+
# In general, only the root logger will not be accessible via its name.
|
| 1771 |
+
# However, the root logger's class has its own __reduce__ method.
|
| 1772 |
+
if getLogger(self.name) is not self:
|
| 1773 |
+
import pickle
|
| 1774 |
+
raise pickle.PicklingError('logger cannot be pickled')
|
| 1775 |
+
return getLogger, (self.name,)
|
| 1776 |
+
|
| 1777 |
+
|
| 1778 |
+
class RootLogger(Logger):
|
| 1779 |
+
"""
|
| 1780 |
+
A root logger is not that different to any other logger, except that
|
| 1781 |
+
it must have a logging level and there is only one instance of it in
|
| 1782 |
+
the hierarchy.
|
| 1783 |
+
"""
|
| 1784 |
+
def __init__(self, level):
|
| 1785 |
+
"""
|
| 1786 |
+
Initialize the logger with the name "root".
|
| 1787 |
+
"""
|
| 1788 |
+
Logger.__init__(self, "root", level)
|
| 1789 |
+
|
| 1790 |
+
def __reduce__(self):
|
| 1791 |
+
return getLogger, ()
|
| 1792 |
+
|
| 1793 |
+
_loggerClass = Logger
|
| 1794 |
+
|
| 1795 |
+
class LoggerAdapter(object):
|
| 1796 |
+
"""
|
| 1797 |
+
An adapter for loggers which makes it easier to specify contextual
|
| 1798 |
+
information in logging output.
|
| 1799 |
+
"""
|
| 1800 |
+
|
| 1801 |
+
def __init__(self, logger, extra=None):
|
| 1802 |
+
"""
|
| 1803 |
+
Initialize the adapter with a logger and a dict-like object which
|
| 1804 |
+
provides contextual information. This constructor signature allows
|
| 1805 |
+
easy stacking of LoggerAdapters, if so desired.
|
| 1806 |
+
|
| 1807 |
+
You can effectively pass keyword arguments as shown in the
|
| 1808 |
+
following example:
|
| 1809 |
+
|
| 1810 |
+
adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))
|
| 1811 |
+
"""
|
| 1812 |
+
self.logger = logger
|
| 1813 |
+
self.extra = extra
|
| 1814 |
+
|
| 1815 |
+
def process(self, msg, kwargs):
|
| 1816 |
+
"""
|
| 1817 |
+
Process the logging message and keyword arguments passed in to
|
| 1818 |
+
a logging call to insert contextual information. You can either
|
| 1819 |
+
manipulate the message itself, the keyword args or both. Return
|
| 1820 |
+
the message and kwargs modified (or not) to suit your needs.
|
| 1821 |
+
|
| 1822 |
+
Normally, you'll only need to override this one method in a
|
| 1823 |
+
LoggerAdapter subclass for your specific needs.
|
| 1824 |
+
"""
|
| 1825 |
+
kwargs["extra"] = self.extra
|
| 1826 |
+
return msg, kwargs
|
| 1827 |
+
|
| 1828 |
+
#
|
| 1829 |
+
# Boilerplate convenience methods
|
| 1830 |
+
#
|
| 1831 |
+
def debug(self, msg, *args, **kwargs):
|
| 1832 |
+
"""
|
| 1833 |
+
Delegate a debug call to the underlying logger.
|
| 1834 |
+
"""
|
| 1835 |
+
self.log(DEBUG, msg, *args, **kwargs)
|
| 1836 |
+
|
| 1837 |
+
def info(self, msg, *args, **kwargs):
|
| 1838 |
+
"""
|
| 1839 |
+
Delegate an info call to the underlying logger.
|
| 1840 |
+
"""
|
| 1841 |
+
self.log(INFO, msg, *args, **kwargs)
|
| 1842 |
+
|
| 1843 |
+
def warning(self, msg, *args, **kwargs):
|
| 1844 |
+
"""
|
| 1845 |
+
Delegate a warning call to the underlying logger.
|
| 1846 |
+
"""
|
| 1847 |
+
self.log(WARNING, msg, *args, **kwargs)
|
| 1848 |
+
|
| 1849 |
+
def warn(self, msg, *args, **kwargs):
|
| 1850 |
+
warnings.warn("The 'warn' method is deprecated, "
|
| 1851 |
+
"use 'warning' instead", DeprecationWarning, 2)
|
| 1852 |
+
self.warning(msg, *args, **kwargs)
|
| 1853 |
+
|
| 1854 |
+
def error(self, msg, *args, **kwargs):
|
| 1855 |
+
"""
|
| 1856 |
+
Delegate an error call to the underlying logger.
|
| 1857 |
+
"""
|
| 1858 |
+
self.log(ERROR, msg, *args, **kwargs)
|
| 1859 |
+
|
| 1860 |
+
def exception(self, msg, *args, exc_info=True, **kwargs):
|
| 1861 |
+
"""
|
| 1862 |
+
Delegate an exception call to the underlying logger.
|
| 1863 |
+
"""
|
| 1864 |
+
self.log(ERROR, msg, *args, exc_info=exc_info, **kwargs)
|
| 1865 |
+
|
| 1866 |
+
def critical(self, msg, *args, **kwargs):
|
| 1867 |
+
"""
|
| 1868 |
+
Delegate a critical call to the underlying logger.
|
| 1869 |
+
"""
|
| 1870 |
+
self.log(CRITICAL, msg, *args, **kwargs)
|
| 1871 |
+
|
| 1872 |
+
def log(self, level, msg, *args, **kwargs):
|
| 1873 |
+
"""
|
| 1874 |
+
Delegate a log call to the underlying logger, after adding
|
| 1875 |
+
contextual information from this adapter instance.
|
| 1876 |
+
"""
|
| 1877 |
+
if self.isEnabledFor(level):
|
| 1878 |
+
msg, kwargs = self.process(msg, kwargs)
|
| 1879 |
+
self.logger.log(level, msg, *args, **kwargs)
|
| 1880 |
+
|
| 1881 |
+
def isEnabledFor(self, level):
|
| 1882 |
+
"""
|
| 1883 |
+
Is this logger enabled for level 'level'?
|
| 1884 |
+
"""
|
| 1885 |
+
return self.logger.isEnabledFor(level)
|
| 1886 |
+
|
| 1887 |
+
def setLevel(self, level):
|
| 1888 |
+
"""
|
| 1889 |
+
Set the specified level on the underlying logger.
|
| 1890 |
+
"""
|
| 1891 |
+
self.logger.setLevel(level)
|
| 1892 |
+
|
| 1893 |
+
def getEffectiveLevel(self):
|
| 1894 |
+
"""
|
| 1895 |
+
Get the effective level for the underlying logger.
|
| 1896 |
+
"""
|
| 1897 |
+
return self.logger.getEffectiveLevel()
|
| 1898 |
+
|
| 1899 |
+
def hasHandlers(self):
|
| 1900 |
+
"""
|
| 1901 |
+
See if the underlying logger has any handlers.
|
| 1902 |
+
"""
|
| 1903 |
+
return self.logger.hasHandlers()
|
| 1904 |
+
|
| 1905 |
+
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
|
| 1906 |
+
"""
|
| 1907 |
+
Low-level log implementation, proxied to allow nested logger adapters.
|
| 1908 |
+
"""
|
| 1909 |
+
return self.logger._log(
|
| 1910 |
+
level,
|
| 1911 |
+
msg,
|
| 1912 |
+
args,
|
| 1913 |
+
exc_info=exc_info,
|
| 1914 |
+
extra=extra,
|
| 1915 |
+
stack_info=stack_info,
|
| 1916 |
+
)
|
| 1917 |
+
|
| 1918 |
+
@property
|
| 1919 |
+
def manager(self):
|
| 1920 |
+
return self.logger.manager
|
| 1921 |
+
|
| 1922 |
+
@manager.setter
|
| 1923 |
+
def manager(self, value):
|
| 1924 |
+
self.logger.manager = value
|
| 1925 |
+
|
| 1926 |
+
@property
|
| 1927 |
+
def name(self):
|
| 1928 |
+
return self.logger.name
|
| 1929 |
+
|
| 1930 |
+
def __repr__(self):
|
| 1931 |
+
logger = self.logger
|
| 1932 |
+
level = getLevelName(logger.getEffectiveLevel())
|
| 1933 |
+
return '<%s %s (%s)>' % (self.__class__.__name__, logger.name, level)
|
| 1934 |
+
|
| 1935 |
+
root = RootLogger(WARNING)
|
| 1936 |
+
Logger.root = root
|
| 1937 |
+
Logger.manager = Manager(Logger.root)
|
| 1938 |
+
|
| 1939 |
+
#---------------------------------------------------------------------------
|
| 1940 |
+
# Configuration classes and functions
|
| 1941 |
+
#---------------------------------------------------------------------------
|
| 1942 |
+
|
| 1943 |
+
def basicConfig(**kwargs):
|
| 1944 |
+
"""
|
| 1945 |
+
Do basic configuration for the logging system.
|
| 1946 |
+
|
| 1947 |
+
This function does nothing if the root logger already has handlers
|
| 1948 |
+
configured, unless the keyword argument *force* is set to ``True``.
|
| 1949 |
+
It is a convenience method intended for use by simple scripts
|
| 1950 |
+
to do one-shot configuration of the logging package.
|
| 1951 |
+
|
| 1952 |
+
The default behaviour is to create a StreamHandler which writes to
|
| 1953 |
+
sys.stderr, set a formatter using the BASIC_FORMAT format string, and
|
| 1954 |
+
add the handler to the root logger.
|
| 1955 |
+
|
| 1956 |
+
A number of optional keyword arguments may be specified, which can alter
|
| 1957 |
+
the default behaviour.
|
| 1958 |
+
|
| 1959 |
+
filename Specifies that a FileHandler be created, using the specified
|
| 1960 |
+
filename, rather than a StreamHandler.
|
| 1961 |
+
filemode Specifies the mode to open the file, if filename is specified
|
| 1962 |
+
(if filemode is unspecified, it defaults to 'a').
|
| 1963 |
+
format Use the specified format string for the handler.
|
| 1964 |
+
datefmt Use the specified date/time format.
|
| 1965 |
+
style If a format string is specified, use this to specify the
|
| 1966 |
+
type of format string (possible values '%', '{', '$', for
|
| 1967 |
+
%-formatting, :meth:`str.format` and :class:`string.Template`
|
| 1968 |
+
- defaults to '%').
|
| 1969 |
+
level Set the root logger level to the specified level.
|
| 1970 |
+
stream Use the specified stream to initialize the StreamHandler. Note
|
| 1971 |
+
that this argument is incompatible with 'filename' - if both
|
| 1972 |
+
are present, 'stream' is ignored.
|
| 1973 |
+
handlers If specified, this should be an iterable of already created
|
| 1974 |
+
handlers, which will be added to the root handler. Any handler
|
| 1975 |
+
in the list which does not have a formatter assigned will be
|
| 1976 |
+
assigned the formatter created in this function.
|
| 1977 |
+
force If this keyword is specified as true, any existing handlers
|
| 1978 |
+
attached to the root logger are removed and closed, before
|
| 1979 |
+
carrying out the configuration as specified by the other
|
| 1980 |
+
arguments.
|
| 1981 |
+
encoding If specified together with a filename, this encoding is passed to
|
| 1982 |
+
the created FileHandler, causing it to be used when the file is
|
| 1983 |
+
opened.
|
| 1984 |
+
errors If specified together with a filename, this value is passed to the
|
| 1985 |
+
created FileHandler, causing it to be used when the file is
|
| 1986 |
+
opened in text mode. If not specified, the default value is
|
| 1987 |
+
`backslashreplace`.
|
| 1988 |
+
|
| 1989 |
+
Note that you could specify a stream created using open(filename, mode)
|
| 1990 |
+
rather than passing the filename and mode in. However, it should be
|
| 1991 |
+
remembered that StreamHandler does not close its stream (since it may be
|
| 1992 |
+
using sys.stdout or sys.stderr), whereas FileHandler closes its stream
|
| 1993 |
+
when the handler is closed.
|
| 1994 |
+
|
| 1995 |
+
.. versionchanged:: 3.2
|
| 1996 |
+
Added the ``style`` parameter.
|
| 1997 |
+
|
| 1998 |
+
.. versionchanged:: 3.3
|
| 1999 |
+
Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
|
| 2000 |
+
incompatible arguments (e.g. ``handlers`` specified together with
|
| 2001 |
+
``filename``/``filemode``, or ``filename``/``filemode`` specified
|
| 2002 |
+
together with ``stream``, or ``handlers`` specified together with
|
| 2003 |
+
``stream``.
|
| 2004 |
+
|
| 2005 |
+
.. versionchanged:: 3.8
|
| 2006 |
+
Added the ``force`` parameter.
|
| 2007 |
+
|
| 2008 |
+
.. versionchanged:: 3.9
|
| 2009 |
+
Added the ``encoding`` and ``errors`` parameters.
|
| 2010 |
+
"""
|
| 2011 |
+
# Add thread safety in case someone mistakenly calls
|
| 2012 |
+
# basicConfig() from multiple threads
|
| 2013 |
+
_acquireLock()
|
| 2014 |
+
try:
|
| 2015 |
+
force = kwargs.pop('force', False)
|
| 2016 |
+
encoding = kwargs.pop('encoding', None)
|
| 2017 |
+
errors = kwargs.pop('errors', 'backslashreplace')
|
| 2018 |
+
if force:
|
| 2019 |
+
for h in root.handlers[:]:
|
| 2020 |
+
root.removeHandler(h)
|
| 2021 |
+
h.close()
|
| 2022 |
+
if len(root.handlers) == 0:
|
| 2023 |
+
handlers = kwargs.pop("handlers", None)
|
| 2024 |
+
if handlers is None:
|
| 2025 |
+
if "stream" in kwargs and "filename" in kwargs:
|
| 2026 |
+
raise ValueError("'stream' and 'filename' should not be "
|
| 2027 |
+
"specified together")
|
| 2028 |
+
else:
|
| 2029 |
+
if "stream" in kwargs or "filename" in kwargs:
|
| 2030 |
+
raise ValueError("'stream' or 'filename' should not be "
|
| 2031 |
+
"specified together with 'handlers'")
|
| 2032 |
+
if handlers is None:
|
| 2033 |
+
filename = kwargs.pop("filename", None)
|
| 2034 |
+
mode = kwargs.pop("filemode", 'a')
|
| 2035 |
+
if filename:
|
| 2036 |
+
if 'b' in mode:
|
| 2037 |
+
errors = None
|
| 2038 |
+
else:
|
| 2039 |
+
encoding = io.text_encoding(encoding)
|
| 2040 |
+
h = FileHandler(filename, mode,
|
| 2041 |
+
encoding=encoding, errors=errors)
|
| 2042 |
+
else:
|
| 2043 |
+
stream = kwargs.pop("stream", None)
|
| 2044 |
+
h = StreamHandler(stream)
|
| 2045 |
+
handlers = [h]
|
| 2046 |
+
dfs = kwargs.pop("datefmt", None)
|
| 2047 |
+
style = kwargs.pop("style", '%')
|
| 2048 |
+
if style not in _STYLES:
|
| 2049 |
+
raise ValueError('Style must be one of: %s' % ','.join(
|
| 2050 |
+
_STYLES.keys()))
|
| 2051 |
+
fs = kwargs.pop("format", _STYLES[style][1])
|
| 2052 |
+
fmt = Formatter(fs, dfs, style)
|
| 2053 |
+
for h in handlers:
|
| 2054 |
+
if h.formatter is None:
|
| 2055 |
+
h.setFormatter(fmt)
|
| 2056 |
+
root.addHandler(h)
|
| 2057 |
+
level = kwargs.pop("level", None)
|
| 2058 |
+
if level is not None:
|
| 2059 |
+
root.setLevel(level)
|
| 2060 |
+
if kwargs:
|
| 2061 |
+
keys = ', '.join(kwargs.keys())
|
| 2062 |
+
raise ValueError('Unrecognised argument(s): %s' % keys)
|
| 2063 |
+
finally:
|
| 2064 |
+
_releaseLock()
|
| 2065 |
+
|
| 2066 |
+
#---------------------------------------------------------------------------
|
| 2067 |
+
# Utility functions at module level.
|
| 2068 |
+
# Basically delegate everything to the root logger.
|
| 2069 |
+
#---------------------------------------------------------------------------
|
| 2070 |
+
|
| 2071 |
+
def getLogger(name=None):
|
| 2072 |
+
"""
|
| 2073 |
+
Return a logger with the specified name, creating it if necessary.
|
| 2074 |
+
|
| 2075 |
+
If no name is specified, return the root logger.
|
| 2076 |
+
"""
|
| 2077 |
+
if not name or isinstance(name, str) and name == root.name:
|
| 2078 |
+
return root
|
| 2079 |
+
return Logger.manager.getLogger(name)
|
| 2080 |
+
|
| 2081 |
+
def critical(msg, *args, **kwargs):
|
| 2082 |
+
"""
|
| 2083 |
+
Log a message with severity 'CRITICAL' on the root logger. If the logger
|
| 2084 |
+
has no handlers, call basicConfig() to add a console handler with a
|
| 2085 |
+
pre-defined format.
|
| 2086 |
+
"""
|
| 2087 |
+
if len(root.handlers) == 0:
|
| 2088 |
+
basicConfig()
|
| 2089 |
+
root.critical(msg, *args, **kwargs)
|
| 2090 |
+
|
| 2091 |
+
def fatal(msg, *args, **kwargs):
|
| 2092 |
+
"""
|
| 2093 |
+
Don't use this function, use critical() instead.
|
| 2094 |
+
"""
|
| 2095 |
+
critical(msg, *args, **kwargs)
|
| 2096 |
+
|
| 2097 |
+
def error(msg, *args, **kwargs):
|
| 2098 |
+
"""
|
| 2099 |
+
Log a message with severity 'ERROR' on the root logger. If the logger has
|
| 2100 |
+
no handlers, call basicConfig() to add a console handler with a pre-defined
|
| 2101 |
+
format.
|
| 2102 |
+
"""
|
| 2103 |
+
if len(root.handlers) == 0:
|
| 2104 |
+
basicConfig()
|
| 2105 |
+
root.error(msg, *args, **kwargs)
|
| 2106 |
+
|
| 2107 |
+
def exception(msg, *args, exc_info=True, **kwargs):
|
| 2108 |
+
"""
|
| 2109 |
+
Log a message with severity 'ERROR' on the root logger, with exception
|
| 2110 |
+
information. If the logger has no handlers, basicConfig() is called to add
|
| 2111 |
+
a console handler with a pre-defined format.
|
| 2112 |
+
"""
|
| 2113 |
+
error(msg, *args, exc_info=exc_info, **kwargs)
|
| 2114 |
+
|
| 2115 |
+
def warning(msg, *args, **kwargs):
|
| 2116 |
+
"""
|
| 2117 |
+
Log a message with severity 'WARNING' on the root logger. If the logger has
|
| 2118 |
+
no handlers, call basicConfig() to add a console handler with a pre-defined
|
| 2119 |
+
format.
|
| 2120 |
+
"""
|
| 2121 |
+
if len(root.handlers) == 0:
|
| 2122 |
+
basicConfig()
|
| 2123 |
+
root.warning(msg, *args, **kwargs)
|
| 2124 |
+
|
| 2125 |
+
def warn(msg, *args, **kwargs):
|
| 2126 |
+
warnings.warn("The 'warn' function is deprecated, "
|
| 2127 |
+
"use 'warning' instead", DeprecationWarning, 2)
|
| 2128 |
+
warning(msg, *args, **kwargs)
|
| 2129 |
+
|
| 2130 |
+
def info(msg, *args, **kwargs):
|
| 2131 |
+
"""
|
| 2132 |
+
Log a message with severity 'INFO' on the root logger. If the logger has
|
| 2133 |
+
no handlers, call basicConfig() to add a console handler with a pre-defined
|
| 2134 |
+
format.
|
| 2135 |
+
"""
|
| 2136 |
+
if len(root.handlers) == 0:
|
| 2137 |
+
basicConfig()
|
| 2138 |
+
root.info(msg, *args, **kwargs)
|
| 2139 |
+
|
| 2140 |
+
def debug(msg, *args, **kwargs):
|
| 2141 |
+
"""
|
| 2142 |
+
Log a message with severity 'DEBUG' on the root logger. If the logger has
|
| 2143 |
+
no handlers, call basicConfig() to add a console handler with a pre-defined
|
| 2144 |
+
format.
|
| 2145 |
+
"""
|
| 2146 |
+
if len(root.handlers) == 0:
|
| 2147 |
+
basicConfig()
|
| 2148 |
+
root.debug(msg, *args, **kwargs)
|
| 2149 |
+
|
| 2150 |
+
def log(level, msg, *args, **kwargs):
|
| 2151 |
+
"""
|
| 2152 |
+
Log 'msg % args' with the integer severity 'level' on the root logger. If
|
| 2153 |
+
the logger has no handlers, call basicConfig() to add a console handler
|
| 2154 |
+
with a pre-defined format.
|
| 2155 |
+
"""
|
| 2156 |
+
if len(root.handlers) == 0:
|
| 2157 |
+
basicConfig()
|
| 2158 |
+
root.log(level, msg, *args, **kwargs)
|
| 2159 |
+
|
| 2160 |
+
def disable(level=CRITICAL):
|
| 2161 |
+
"""
|
| 2162 |
+
Disable all logging calls of severity 'level' and below.
|
| 2163 |
+
"""
|
| 2164 |
+
root.manager.disable = level
|
| 2165 |
+
root.manager._clear_cache()
|
| 2166 |
+
|
| 2167 |
+
def shutdown(handlerList=_handlerList):
|
| 2168 |
+
"""
|
| 2169 |
+
Perform any cleanup actions in the logging system (e.g. flushing
|
| 2170 |
+
buffers).
|
| 2171 |
+
|
| 2172 |
+
Should be called at application exit.
|
| 2173 |
+
"""
|
| 2174 |
+
for wr in reversed(handlerList[:]):
|
| 2175 |
+
#errors might occur, for example, if files are locked
|
| 2176 |
+
#we just ignore them if raiseExceptions is not set
|
| 2177 |
+
try:
|
| 2178 |
+
h = wr()
|
| 2179 |
+
if h:
|
| 2180 |
+
try:
|
| 2181 |
+
h.acquire()
|
| 2182 |
+
h.flush()
|
| 2183 |
+
h.close()
|
| 2184 |
+
except (OSError, ValueError):
|
| 2185 |
+
# Ignore errors which might be caused
|
| 2186 |
+
# because handlers have been closed but
|
| 2187 |
+
# references to them are still around at
|
| 2188 |
+
# application exit.
|
| 2189 |
+
pass
|
| 2190 |
+
finally:
|
| 2191 |
+
h.release()
|
| 2192 |
+
except: # ignore everything, as we're shutting down
|
| 2193 |
+
if raiseExceptions:
|
| 2194 |
+
raise
|
| 2195 |
+
#else, swallow
|
| 2196 |
+
|
| 2197 |
+
#Let's try and shutdown automatically on application exit...
|
| 2198 |
+
import atexit
|
| 2199 |
+
atexit.register(shutdown)
|
| 2200 |
+
|
| 2201 |
+
# Null handler
|
| 2202 |
+
|
| 2203 |
+
class NullHandler(Handler):
|
| 2204 |
+
"""
|
| 2205 |
+
This handler does nothing. It's intended to be used to avoid the
|
| 2206 |
+
"No handlers could be found for logger XXX" one-off warning. This is
|
| 2207 |
+
important for library code, which may contain code to log events. If a user
|
| 2208 |
+
of the library does not configure logging, the one-off warning might be
|
| 2209 |
+
produced; to avoid this, the library developer simply needs to instantiate
|
| 2210 |
+
a NullHandler and add it to the top-level logger of the library module or
|
| 2211 |
+
package.
|
| 2212 |
+
"""
|
| 2213 |
+
def handle(self, record):
|
| 2214 |
+
"""Stub."""
|
| 2215 |
+
|
| 2216 |
+
def emit(self, record):
|
| 2217 |
+
"""Stub."""
|
| 2218 |
+
|
| 2219 |
+
def createLock(self):
|
| 2220 |
+
self.lock = None
|
| 2221 |
+
|
| 2222 |
+
def _at_fork_reinit(self):
|
| 2223 |
+
pass
|
| 2224 |
+
|
| 2225 |
+
# Warnings integration
|
| 2226 |
+
|
| 2227 |
+
_warnings_showwarning = None
|
| 2228 |
+
|
| 2229 |
+
def _showwarning(message, category, filename, lineno, file=None, line=None):
|
| 2230 |
+
"""
|
| 2231 |
+
Implementation of showwarnings which redirects to logging, which will first
|
| 2232 |
+
check to see if the file parameter is None. If a file is specified, it will
|
| 2233 |
+
delegate to the original warnings implementation of showwarning. Otherwise,
|
| 2234 |
+
it will call warnings.formatwarning and will log the resulting string to a
|
| 2235 |
+
warnings logger named "py.warnings" with level logging.WARNING.
|
| 2236 |
+
"""
|
| 2237 |
+
if file is not None:
|
| 2238 |
+
if _warnings_showwarning is not None:
|
| 2239 |
+
_warnings_showwarning(message, category, filename, lineno, file, line)
|
| 2240 |
+
else:
|
| 2241 |
+
s = warnings.formatwarning(message, category, filename, lineno, line)
|
| 2242 |
+
logger = getLogger("py.warnings")
|
| 2243 |
+
if not logger.handlers:
|
| 2244 |
+
logger.addHandler(NullHandler())
|
| 2245 |
+
logger.warning("%s", s)
|
| 2246 |
+
|
| 2247 |
+
def captureWarnings(capture):
|
| 2248 |
+
"""
|
| 2249 |
+
If capture is true, redirect all warnings to the logging package.
|
| 2250 |
+
If capture is False, ensure that warnings are not redirected to logging
|
| 2251 |
+
but to their original destinations.
|
| 2252 |
+
"""
|
| 2253 |
+
global _warnings_showwarning
|
| 2254 |
+
if capture:
|
| 2255 |
+
if _warnings_showwarning is None:
|
| 2256 |
+
_warnings_showwarning = warnings.showwarning
|
| 2257 |
+
warnings.showwarning = _showwarning
|
| 2258 |
+
else:
|
| 2259 |
+
if _warnings_showwarning is not None:
|
| 2260 |
+
warnings.showwarning = _warnings_showwarning
|
| 2261 |
+
_warnings_showwarning = None
|
miniconda3/envs/ladir/lib/python3.10/logging/config.py
ADDED
|
@@ -0,0 +1,947 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
# documentation for any purpose and without fee is hereby granted,
|
| 5 |
+
# provided that the above copyright notice appear in all copies and that
|
| 6 |
+
# both that copyright notice and this permission notice appear in
|
| 7 |
+
# supporting documentation, and that the name of Vinay Sajip
|
| 8 |
+
# not be used in advertising or publicity pertaining to distribution
|
| 9 |
+
# of the software without specific, written prior permission.
|
| 10 |
+
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
|
| 11 |
+
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
|
| 12 |
+
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
|
| 13 |
+
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
|
| 14 |
+
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 15 |
+
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
Configuration functions for the logging package for Python. The core package
|
| 19 |
+
is based on PEP 282 and comments thereto in comp.lang.python, and influenced
|
| 20 |
+
by Apache's log4j system.
|
| 21 |
+
|
| 22 |
+
Copyright (C) 2001-2019 Vinay Sajip. All Rights Reserved.
|
| 23 |
+
|
| 24 |
+
To use, simply 'import logging' and log away!
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
import errno
|
| 28 |
+
import io
|
| 29 |
+
import logging
|
| 30 |
+
import logging.handlers
|
| 31 |
+
import re
|
| 32 |
+
import struct
|
| 33 |
+
import sys
|
| 34 |
+
import threading
|
| 35 |
+
import traceback
|
| 36 |
+
|
| 37 |
+
from socketserver import ThreadingTCPServer, StreamRequestHandler
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
DEFAULT_LOGGING_CONFIG_PORT = 9030
|
| 41 |
+
|
| 42 |
+
RESET_ERROR = errno.ECONNRESET
|
| 43 |
+
|
| 44 |
+
#
|
| 45 |
+
# The following code implements a socket listener for on-the-fly
|
| 46 |
+
# reconfiguration of logging.
|
| 47 |
+
#
|
| 48 |
+
# _listener holds the server object doing the listening
|
| 49 |
+
_listener = None
|
| 50 |
+
|
| 51 |
+
def fileConfig(fname, defaults=None, disable_existing_loggers=True, encoding=None):
|
| 52 |
+
"""
|
| 53 |
+
Read the logging configuration from a ConfigParser-format file.
|
| 54 |
+
|
| 55 |
+
This can be called several times from an application, allowing an end user
|
| 56 |
+
the ability to select from various pre-canned configurations (if the
|
| 57 |
+
developer provides a mechanism to present the choices and load the chosen
|
| 58 |
+
configuration).
|
| 59 |
+
"""
|
| 60 |
+
import configparser
|
| 61 |
+
|
| 62 |
+
if isinstance(fname, configparser.RawConfigParser):
|
| 63 |
+
cp = fname
|
| 64 |
+
else:
|
| 65 |
+
cp = configparser.ConfigParser(defaults)
|
| 66 |
+
if hasattr(fname, 'readline'):
|
| 67 |
+
cp.read_file(fname)
|
| 68 |
+
else:
|
| 69 |
+
encoding = io.text_encoding(encoding)
|
| 70 |
+
cp.read(fname, encoding=encoding)
|
| 71 |
+
|
| 72 |
+
formatters = _create_formatters(cp)
|
| 73 |
+
|
| 74 |
+
# critical section
|
| 75 |
+
logging._acquireLock()
|
| 76 |
+
try:
|
| 77 |
+
_clearExistingHandlers()
|
| 78 |
+
|
| 79 |
+
# Handlers add themselves to logging._handlers
|
| 80 |
+
handlers = _install_handlers(cp, formatters)
|
| 81 |
+
_install_loggers(cp, handlers, disable_existing_loggers)
|
| 82 |
+
finally:
|
| 83 |
+
logging._releaseLock()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _resolve(name):
|
| 87 |
+
"""Resolve a dotted name to a global object."""
|
| 88 |
+
name = name.split('.')
|
| 89 |
+
used = name.pop(0)
|
| 90 |
+
found = __import__(used)
|
| 91 |
+
for n in name:
|
| 92 |
+
used = used + '.' + n
|
| 93 |
+
try:
|
| 94 |
+
found = getattr(found, n)
|
| 95 |
+
except AttributeError:
|
| 96 |
+
__import__(used)
|
| 97 |
+
found = getattr(found, n)
|
| 98 |
+
return found
|
| 99 |
+
|
| 100 |
+
def _strip_spaces(alist):
|
| 101 |
+
return map(str.strip, alist)
|
| 102 |
+
|
| 103 |
+
def _create_formatters(cp):
|
| 104 |
+
"""Create and return formatters"""
|
| 105 |
+
flist = cp["formatters"]["keys"]
|
| 106 |
+
if not len(flist):
|
| 107 |
+
return {}
|
| 108 |
+
flist = flist.split(",")
|
| 109 |
+
flist = _strip_spaces(flist)
|
| 110 |
+
formatters = {}
|
| 111 |
+
for form in flist:
|
| 112 |
+
sectname = "formatter_%s" % form
|
| 113 |
+
fs = cp.get(sectname, "format", raw=True, fallback=None)
|
| 114 |
+
dfs = cp.get(sectname, "datefmt", raw=True, fallback=None)
|
| 115 |
+
stl = cp.get(sectname, "style", raw=True, fallback='%')
|
| 116 |
+
c = logging.Formatter
|
| 117 |
+
class_name = cp[sectname].get("class")
|
| 118 |
+
if class_name:
|
| 119 |
+
c = _resolve(class_name)
|
| 120 |
+
f = c(fs, dfs, stl)
|
| 121 |
+
formatters[form] = f
|
| 122 |
+
return formatters
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _install_handlers(cp, formatters):
|
| 126 |
+
"""Install and return handlers"""
|
| 127 |
+
hlist = cp["handlers"]["keys"]
|
| 128 |
+
if not len(hlist):
|
| 129 |
+
return {}
|
| 130 |
+
hlist = hlist.split(",")
|
| 131 |
+
hlist = _strip_spaces(hlist)
|
| 132 |
+
handlers = {}
|
| 133 |
+
fixups = [] #for inter-handler references
|
| 134 |
+
for hand in hlist:
|
| 135 |
+
section = cp["handler_%s" % hand]
|
| 136 |
+
klass = section["class"]
|
| 137 |
+
fmt = section.get("formatter", "")
|
| 138 |
+
try:
|
| 139 |
+
klass = eval(klass, vars(logging))
|
| 140 |
+
except (AttributeError, NameError):
|
| 141 |
+
klass = _resolve(klass)
|
| 142 |
+
args = section.get("args", '()')
|
| 143 |
+
args = eval(args, vars(logging))
|
| 144 |
+
kwargs = section.get("kwargs", '{}')
|
| 145 |
+
kwargs = eval(kwargs, vars(logging))
|
| 146 |
+
h = klass(*args, **kwargs)
|
| 147 |
+
h.name = hand
|
| 148 |
+
if "level" in section:
|
| 149 |
+
level = section["level"]
|
| 150 |
+
h.setLevel(level)
|
| 151 |
+
if len(fmt):
|
| 152 |
+
h.setFormatter(formatters[fmt])
|
| 153 |
+
if issubclass(klass, logging.handlers.MemoryHandler):
|
| 154 |
+
target = section.get("target", "")
|
| 155 |
+
if len(target): #the target handler may not be loaded yet, so keep for later...
|
| 156 |
+
fixups.append((h, target))
|
| 157 |
+
handlers[hand] = h
|
| 158 |
+
#now all handlers are loaded, fixup inter-handler references...
|
| 159 |
+
for h, t in fixups:
|
| 160 |
+
h.setTarget(handlers[t])
|
| 161 |
+
return handlers
|
| 162 |
+
|
| 163 |
+
def _handle_existing_loggers(existing, child_loggers, disable_existing):
|
| 164 |
+
"""
|
| 165 |
+
When (re)configuring logging, handle loggers which were in the previous
|
| 166 |
+
configuration but are not in the new configuration. There's no point
|
| 167 |
+
deleting them as other threads may continue to hold references to them;
|
| 168 |
+
and by disabling them, you stop them doing any logging.
|
| 169 |
+
|
| 170 |
+
However, don't disable children of named loggers, as that's probably not
|
| 171 |
+
what was intended by the user. Also, allow existing loggers to NOT be
|
| 172 |
+
disabled if disable_existing is false.
|
| 173 |
+
"""
|
| 174 |
+
root = logging.root
|
| 175 |
+
for log in existing:
|
| 176 |
+
logger = root.manager.loggerDict[log]
|
| 177 |
+
if log in child_loggers:
|
| 178 |
+
if not isinstance(logger, logging.PlaceHolder):
|
| 179 |
+
logger.setLevel(logging.NOTSET)
|
| 180 |
+
logger.handlers = []
|
| 181 |
+
logger.propagate = True
|
| 182 |
+
else:
|
| 183 |
+
logger.disabled = disable_existing
|
| 184 |
+
|
| 185 |
+
def _install_loggers(cp, handlers, disable_existing):
|
| 186 |
+
"""Create and install loggers"""
|
| 187 |
+
|
| 188 |
+
# configure the root first
|
| 189 |
+
llist = cp["loggers"]["keys"]
|
| 190 |
+
llist = llist.split(",")
|
| 191 |
+
llist = list(_strip_spaces(llist))
|
| 192 |
+
llist.remove("root")
|
| 193 |
+
section = cp["logger_root"]
|
| 194 |
+
root = logging.root
|
| 195 |
+
log = root
|
| 196 |
+
if "level" in section:
|
| 197 |
+
level = section["level"]
|
| 198 |
+
log.setLevel(level)
|
| 199 |
+
for h in root.handlers[:]:
|
| 200 |
+
root.removeHandler(h)
|
| 201 |
+
hlist = section["handlers"]
|
| 202 |
+
if len(hlist):
|
| 203 |
+
hlist = hlist.split(",")
|
| 204 |
+
hlist = _strip_spaces(hlist)
|
| 205 |
+
for hand in hlist:
|
| 206 |
+
log.addHandler(handlers[hand])
|
| 207 |
+
|
| 208 |
+
#and now the others...
|
| 209 |
+
#we don't want to lose the existing loggers,
|
| 210 |
+
#since other threads may have pointers to them.
|
| 211 |
+
#existing is set to contain all existing loggers,
|
| 212 |
+
#and as we go through the new configuration we
|
| 213 |
+
#remove any which are configured. At the end,
|
| 214 |
+
#what's left in existing is the set of loggers
|
| 215 |
+
#which were in the previous configuration but
|
| 216 |
+
#which are not in the new configuration.
|
| 217 |
+
existing = list(root.manager.loggerDict.keys())
|
| 218 |
+
#The list needs to be sorted so that we can
|
| 219 |
+
#avoid disabling child loggers of explicitly
|
| 220 |
+
#named loggers. With a sorted list it is easier
|
| 221 |
+
#to find the child loggers.
|
| 222 |
+
existing.sort()
|
| 223 |
+
#We'll keep the list of existing loggers
|
| 224 |
+
#which are children of named loggers here...
|
| 225 |
+
child_loggers = []
|
| 226 |
+
#now set up the new ones...
|
| 227 |
+
for log in llist:
|
| 228 |
+
section = cp["logger_%s" % log]
|
| 229 |
+
qn = section["qualname"]
|
| 230 |
+
propagate = section.getint("propagate", fallback=1)
|
| 231 |
+
logger = logging.getLogger(qn)
|
| 232 |
+
if qn in existing:
|
| 233 |
+
i = existing.index(qn) + 1 # start with the entry after qn
|
| 234 |
+
prefixed = qn + "."
|
| 235 |
+
pflen = len(prefixed)
|
| 236 |
+
num_existing = len(existing)
|
| 237 |
+
while i < num_existing:
|
| 238 |
+
if existing[i][:pflen] == prefixed:
|
| 239 |
+
child_loggers.append(existing[i])
|
| 240 |
+
i += 1
|
| 241 |
+
existing.remove(qn)
|
| 242 |
+
if "level" in section:
|
| 243 |
+
level = section["level"]
|
| 244 |
+
logger.setLevel(level)
|
| 245 |
+
for h in logger.handlers[:]:
|
| 246 |
+
logger.removeHandler(h)
|
| 247 |
+
logger.propagate = propagate
|
| 248 |
+
logger.disabled = 0
|
| 249 |
+
hlist = section["handlers"]
|
| 250 |
+
if len(hlist):
|
| 251 |
+
hlist = hlist.split(",")
|
| 252 |
+
hlist = _strip_spaces(hlist)
|
| 253 |
+
for hand in hlist:
|
| 254 |
+
logger.addHandler(handlers[hand])
|
| 255 |
+
|
| 256 |
+
#Disable any old loggers. There's no point deleting
|
| 257 |
+
#them as other threads may continue to hold references
|
| 258 |
+
#and by disabling them, you stop them doing any logging.
|
| 259 |
+
#However, don't disable children of named loggers, as that's
|
| 260 |
+
#probably not what was intended by the user.
|
| 261 |
+
#for log in existing:
|
| 262 |
+
# logger = root.manager.loggerDict[log]
|
| 263 |
+
# if log in child_loggers:
|
| 264 |
+
# logger.level = logging.NOTSET
|
| 265 |
+
# logger.handlers = []
|
| 266 |
+
# logger.propagate = 1
|
| 267 |
+
# elif disable_existing_loggers:
|
| 268 |
+
# logger.disabled = 1
|
| 269 |
+
_handle_existing_loggers(existing, child_loggers, disable_existing)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def _clearExistingHandlers():
|
| 273 |
+
"""Clear and close existing handlers"""
|
| 274 |
+
logging._handlers.clear()
|
| 275 |
+
logging.shutdown(logging._handlerList[:])
|
| 276 |
+
del logging._handlerList[:]
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def valid_ident(s):
|
| 283 |
+
m = IDENTIFIER.match(s)
|
| 284 |
+
if not m:
|
| 285 |
+
raise ValueError('Not a valid Python identifier: %r' % s)
|
| 286 |
+
return True
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
class ConvertingMixin(object):
|
| 290 |
+
"""For ConvertingXXX's, this mixin class provides common functions"""
|
| 291 |
+
|
| 292 |
+
def convert_with_key(self, key, value, replace=True):
|
| 293 |
+
result = self.configurator.convert(value)
|
| 294 |
+
#If the converted value is different, save for next time
|
| 295 |
+
if value is not result:
|
| 296 |
+
if replace:
|
| 297 |
+
self[key] = result
|
| 298 |
+
if type(result) in (ConvertingDict, ConvertingList,
|
| 299 |
+
ConvertingTuple):
|
| 300 |
+
result.parent = self
|
| 301 |
+
result.key = key
|
| 302 |
+
return result
|
| 303 |
+
|
| 304 |
+
def convert(self, value):
|
| 305 |
+
result = self.configurator.convert(value)
|
| 306 |
+
if value is not result:
|
| 307 |
+
if type(result) in (ConvertingDict, ConvertingList,
|
| 308 |
+
ConvertingTuple):
|
| 309 |
+
result.parent = self
|
| 310 |
+
return result
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# The ConvertingXXX classes are wrappers around standard Python containers,
|
| 314 |
+
# and they serve to convert any suitable values in the container. The
|
| 315 |
+
# conversion converts base dicts, lists and tuples to their wrapped
|
| 316 |
+
# equivalents, whereas strings which match a conversion format are converted
|
| 317 |
+
# appropriately.
|
| 318 |
+
#
|
| 319 |
+
# Each wrapper should have a configurator attribute holding the actual
|
| 320 |
+
# configurator to use for conversion.
|
| 321 |
+
|
| 322 |
+
class ConvertingDict(dict, ConvertingMixin):
|
| 323 |
+
"""A converting dictionary wrapper."""
|
| 324 |
+
|
| 325 |
+
def __getitem__(self, key):
|
| 326 |
+
value = dict.__getitem__(self, key)
|
| 327 |
+
return self.convert_with_key(key, value)
|
| 328 |
+
|
| 329 |
+
def get(self, key, default=None):
|
| 330 |
+
value = dict.get(self, key, default)
|
| 331 |
+
return self.convert_with_key(key, value)
|
| 332 |
+
|
| 333 |
+
def pop(self, key, default=None):
|
| 334 |
+
value = dict.pop(self, key, default)
|
| 335 |
+
return self.convert_with_key(key, value, replace=False)
|
| 336 |
+
|
| 337 |
+
class ConvertingList(list, ConvertingMixin):
|
| 338 |
+
"""A converting list wrapper."""
|
| 339 |
+
def __getitem__(self, key):
|
| 340 |
+
value = list.__getitem__(self, key)
|
| 341 |
+
return self.convert_with_key(key, value)
|
| 342 |
+
|
| 343 |
+
def pop(self, idx=-1):
|
| 344 |
+
value = list.pop(self, idx)
|
| 345 |
+
return self.convert(value)
|
| 346 |
+
|
| 347 |
+
class ConvertingTuple(tuple, ConvertingMixin):
|
| 348 |
+
"""A converting tuple wrapper."""
|
| 349 |
+
def __getitem__(self, key):
|
| 350 |
+
value = tuple.__getitem__(self, key)
|
| 351 |
+
# Can't replace a tuple entry.
|
| 352 |
+
return self.convert_with_key(key, value, replace=False)
|
| 353 |
+
|
| 354 |
+
class BaseConfigurator(object):
|
| 355 |
+
"""
|
| 356 |
+
The configurator base class which defines some useful defaults.
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')
|
| 360 |
+
|
| 361 |
+
WORD_PATTERN = re.compile(r'^\s*(\w+)\s*')
|
| 362 |
+
DOT_PATTERN = re.compile(r'^\.\s*(\w+)\s*')
|
| 363 |
+
INDEX_PATTERN = re.compile(r'^\[\s*(\w+)\s*\]\s*')
|
| 364 |
+
DIGIT_PATTERN = re.compile(r'^\d+$')
|
| 365 |
+
|
| 366 |
+
value_converters = {
|
| 367 |
+
'ext' : 'ext_convert',
|
| 368 |
+
'cfg' : 'cfg_convert',
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
# We might want to use a different one, e.g. importlib
|
| 372 |
+
importer = staticmethod(__import__)
|
| 373 |
+
|
| 374 |
+
def __init__(self, config):
|
| 375 |
+
self.config = ConvertingDict(config)
|
| 376 |
+
self.config.configurator = self
|
| 377 |
+
|
| 378 |
+
def resolve(self, s):
|
| 379 |
+
"""
|
| 380 |
+
Resolve strings to objects using standard import and attribute
|
| 381 |
+
syntax.
|
| 382 |
+
"""
|
| 383 |
+
name = s.split('.')
|
| 384 |
+
used = name.pop(0)
|
| 385 |
+
try:
|
| 386 |
+
found = self.importer(used)
|
| 387 |
+
for frag in name:
|
| 388 |
+
used += '.' + frag
|
| 389 |
+
try:
|
| 390 |
+
found = getattr(found, frag)
|
| 391 |
+
except AttributeError:
|
| 392 |
+
self.importer(used)
|
| 393 |
+
found = getattr(found, frag)
|
| 394 |
+
return found
|
| 395 |
+
except ImportError:
|
| 396 |
+
e, tb = sys.exc_info()[1:]
|
| 397 |
+
v = ValueError('Cannot resolve %r: %s' % (s, e))
|
| 398 |
+
v.__cause__, v.__traceback__ = e, tb
|
| 399 |
+
raise v
|
| 400 |
+
|
| 401 |
+
def ext_convert(self, value):
|
| 402 |
+
"""Default converter for the ext:// protocol."""
|
| 403 |
+
return self.resolve(value)
|
| 404 |
+
|
| 405 |
+
def cfg_convert(self, value):
|
| 406 |
+
"""Default converter for the cfg:// protocol."""
|
| 407 |
+
rest = value
|
| 408 |
+
m = self.WORD_PATTERN.match(rest)
|
| 409 |
+
if m is None:
|
| 410 |
+
raise ValueError("Unable to convert %r" % value)
|
| 411 |
+
else:
|
| 412 |
+
rest = rest[m.end():]
|
| 413 |
+
d = self.config[m.groups()[0]]
|
| 414 |
+
#print d, rest
|
| 415 |
+
while rest:
|
| 416 |
+
m = self.DOT_PATTERN.match(rest)
|
| 417 |
+
if m:
|
| 418 |
+
d = d[m.groups()[0]]
|
| 419 |
+
else:
|
| 420 |
+
m = self.INDEX_PATTERN.match(rest)
|
| 421 |
+
if m:
|
| 422 |
+
idx = m.groups()[0]
|
| 423 |
+
if not self.DIGIT_PATTERN.match(idx):
|
| 424 |
+
d = d[idx]
|
| 425 |
+
else:
|
| 426 |
+
try:
|
| 427 |
+
n = int(idx) # try as number first (most likely)
|
| 428 |
+
d = d[n]
|
| 429 |
+
except TypeError:
|
| 430 |
+
d = d[idx]
|
| 431 |
+
if m:
|
| 432 |
+
rest = rest[m.end():]
|
| 433 |
+
else:
|
| 434 |
+
raise ValueError('Unable to convert '
|
| 435 |
+
'%r at %r' % (value, rest))
|
| 436 |
+
#rest should be empty
|
| 437 |
+
return d
|
| 438 |
+
|
| 439 |
+
def convert(self, value):
|
| 440 |
+
"""
|
| 441 |
+
Convert values to an appropriate type. dicts, lists and tuples are
|
| 442 |
+
replaced by their converting alternatives. Strings are checked to
|
| 443 |
+
see if they have a conversion format and are converted if they do.
|
| 444 |
+
"""
|
| 445 |
+
if not isinstance(value, ConvertingDict) and isinstance(value, dict):
|
| 446 |
+
value = ConvertingDict(value)
|
| 447 |
+
value.configurator = self
|
| 448 |
+
elif not isinstance(value, ConvertingList) and isinstance(value, list):
|
| 449 |
+
value = ConvertingList(value)
|
| 450 |
+
value.configurator = self
|
| 451 |
+
elif not isinstance(value, ConvertingTuple) and\
|
| 452 |
+
isinstance(value, tuple) and not hasattr(value, '_fields'):
|
| 453 |
+
value = ConvertingTuple(value)
|
| 454 |
+
value.configurator = self
|
| 455 |
+
elif isinstance(value, str): # str for py3k
|
| 456 |
+
m = self.CONVERT_PATTERN.match(value)
|
| 457 |
+
if m:
|
| 458 |
+
d = m.groupdict()
|
| 459 |
+
prefix = d['prefix']
|
| 460 |
+
converter = self.value_converters.get(prefix, None)
|
| 461 |
+
if converter:
|
| 462 |
+
suffix = d['suffix']
|
| 463 |
+
converter = getattr(self, converter)
|
| 464 |
+
value = converter(suffix)
|
| 465 |
+
return value
|
| 466 |
+
|
| 467 |
+
def configure_custom(self, config):
|
| 468 |
+
"""Configure an object with a user-supplied factory."""
|
| 469 |
+
c = config.pop('()')
|
| 470 |
+
if not callable(c):
|
| 471 |
+
c = self.resolve(c)
|
| 472 |
+
props = config.pop('.', None)
|
| 473 |
+
# Check for valid identifiers
|
| 474 |
+
kwargs = {k: config[k] for k in config if valid_ident(k)}
|
| 475 |
+
result = c(**kwargs)
|
| 476 |
+
if props:
|
| 477 |
+
for name, value in props.items():
|
| 478 |
+
setattr(result, name, value)
|
| 479 |
+
return result
|
| 480 |
+
|
| 481 |
+
def as_tuple(self, value):
|
| 482 |
+
"""Utility function which converts lists to tuples."""
|
| 483 |
+
if isinstance(value, list):
|
| 484 |
+
value = tuple(value)
|
| 485 |
+
return value
|
| 486 |
+
|
| 487 |
+
class DictConfigurator(BaseConfigurator):
|
| 488 |
+
"""
|
| 489 |
+
Configure logging using a dictionary-like object to describe the
|
| 490 |
+
configuration.
|
| 491 |
+
"""
|
| 492 |
+
|
| 493 |
+
def configure(self):
|
| 494 |
+
"""Do the configuration."""
|
| 495 |
+
|
| 496 |
+
config = self.config
|
| 497 |
+
if 'version' not in config:
|
| 498 |
+
raise ValueError("dictionary doesn't specify a version")
|
| 499 |
+
if config['version'] != 1:
|
| 500 |
+
raise ValueError("Unsupported version: %s" % config['version'])
|
| 501 |
+
incremental = config.pop('incremental', False)
|
| 502 |
+
EMPTY_DICT = {}
|
| 503 |
+
logging._acquireLock()
|
| 504 |
+
try:
|
| 505 |
+
if incremental:
|
| 506 |
+
handlers = config.get('handlers', EMPTY_DICT)
|
| 507 |
+
for name in handlers:
|
| 508 |
+
if name not in logging._handlers:
|
| 509 |
+
raise ValueError('No handler found with '
|
| 510 |
+
'name %r' % name)
|
| 511 |
+
else:
|
| 512 |
+
try:
|
| 513 |
+
handler = logging._handlers[name]
|
| 514 |
+
handler_config = handlers[name]
|
| 515 |
+
level = handler_config.get('level', None)
|
| 516 |
+
if level:
|
| 517 |
+
handler.setLevel(logging._checkLevel(level))
|
| 518 |
+
except Exception as e:
|
| 519 |
+
raise ValueError('Unable to configure handler '
|
| 520 |
+
'%r' % name) from e
|
| 521 |
+
loggers = config.get('loggers', EMPTY_DICT)
|
| 522 |
+
for name in loggers:
|
| 523 |
+
try:
|
| 524 |
+
self.configure_logger(name, loggers[name], True)
|
| 525 |
+
except Exception as e:
|
| 526 |
+
raise ValueError('Unable to configure logger '
|
| 527 |
+
'%r' % name) from e
|
| 528 |
+
root = config.get('root', None)
|
| 529 |
+
if root:
|
| 530 |
+
try:
|
| 531 |
+
self.configure_root(root, True)
|
| 532 |
+
except Exception as e:
|
| 533 |
+
raise ValueError('Unable to configure root '
|
| 534 |
+
'logger') from e
|
| 535 |
+
else:
|
| 536 |
+
disable_existing = config.pop('disable_existing_loggers', True)
|
| 537 |
+
|
| 538 |
+
_clearExistingHandlers()
|
| 539 |
+
|
| 540 |
+
# Do formatters first - they don't refer to anything else
|
| 541 |
+
formatters = config.get('formatters', EMPTY_DICT)
|
| 542 |
+
for name in formatters:
|
| 543 |
+
try:
|
| 544 |
+
formatters[name] = self.configure_formatter(
|
| 545 |
+
formatters[name])
|
| 546 |
+
except Exception as e:
|
| 547 |
+
raise ValueError('Unable to configure '
|
| 548 |
+
'formatter %r' % name) from e
|
| 549 |
+
# Next, do filters - they don't refer to anything else, either
|
| 550 |
+
filters = config.get('filters', EMPTY_DICT)
|
| 551 |
+
for name in filters:
|
| 552 |
+
try:
|
| 553 |
+
filters[name] = self.configure_filter(filters[name])
|
| 554 |
+
except Exception as e:
|
| 555 |
+
raise ValueError('Unable to configure '
|
| 556 |
+
'filter %r' % name) from e
|
| 557 |
+
|
| 558 |
+
# Next, do handlers - they refer to formatters and filters
|
| 559 |
+
# As handlers can refer to other handlers, sort the keys
|
| 560 |
+
# to allow a deterministic order of configuration
|
| 561 |
+
handlers = config.get('handlers', EMPTY_DICT)
|
| 562 |
+
deferred = []
|
| 563 |
+
for name in sorted(handlers):
|
| 564 |
+
try:
|
| 565 |
+
handler = self.configure_handler(handlers[name])
|
| 566 |
+
handler.name = name
|
| 567 |
+
handlers[name] = handler
|
| 568 |
+
except Exception as e:
|
| 569 |
+
if 'target not configured yet' in str(e.__cause__):
|
| 570 |
+
deferred.append(name)
|
| 571 |
+
else:
|
| 572 |
+
raise ValueError('Unable to configure handler '
|
| 573 |
+
'%r' % name) from e
|
| 574 |
+
|
| 575 |
+
# Now do any that were deferred
|
| 576 |
+
for name in deferred:
|
| 577 |
+
try:
|
| 578 |
+
handler = self.configure_handler(handlers[name])
|
| 579 |
+
handler.name = name
|
| 580 |
+
handlers[name] = handler
|
| 581 |
+
except Exception as e:
|
| 582 |
+
raise ValueError('Unable to configure handler '
|
| 583 |
+
'%r' % name) from e
|
| 584 |
+
|
| 585 |
+
# Next, do loggers - they refer to handlers and filters
|
| 586 |
+
|
| 587 |
+
#we don't want to lose the existing loggers,
|
| 588 |
+
#since other threads may have pointers to them.
|
| 589 |
+
#existing is set to contain all existing loggers,
|
| 590 |
+
#and as we go through the new configuration we
|
| 591 |
+
#remove any which are configured. At the end,
|
| 592 |
+
#what's left in existing is the set of loggers
|
| 593 |
+
#which were in the previous configuration but
|
| 594 |
+
#which are not in the new configuration.
|
| 595 |
+
root = logging.root
|
| 596 |
+
existing = list(root.manager.loggerDict.keys())
|
| 597 |
+
#The list needs to be sorted so that we can
|
| 598 |
+
#avoid disabling child loggers of explicitly
|
| 599 |
+
#named loggers. With a sorted list it is easier
|
| 600 |
+
#to find the child loggers.
|
| 601 |
+
existing.sort()
|
| 602 |
+
#We'll keep the list of existing loggers
|
| 603 |
+
#which are children of named loggers here...
|
| 604 |
+
child_loggers = []
|
| 605 |
+
#now set up the new ones...
|
| 606 |
+
loggers = config.get('loggers', EMPTY_DICT)
|
| 607 |
+
for name in loggers:
|
| 608 |
+
if name in existing:
|
| 609 |
+
i = existing.index(name) + 1 # look after name
|
| 610 |
+
prefixed = name + "."
|
| 611 |
+
pflen = len(prefixed)
|
| 612 |
+
num_existing = len(existing)
|
| 613 |
+
while i < num_existing:
|
| 614 |
+
if existing[i][:pflen] == prefixed:
|
| 615 |
+
child_loggers.append(existing[i])
|
| 616 |
+
i += 1
|
| 617 |
+
existing.remove(name)
|
| 618 |
+
try:
|
| 619 |
+
self.configure_logger(name, loggers[name])
|
| 620 |
+
except Exception as e:
|
| 621 |
+
raise ValueError('Unable to configure logger '
|
| 622 |
+
'%r' % name) from e
|
| 623 |
+
|
| 624 |
+
#Disable any old loggers. There's no point deleting
|
| 625 |
+
#them as other threads may continue to hold references
|
| 626 |
+
#and by disabling them, you stop them doing any logging.
|
| 627 |
+
#However, don't disable children of named loggers, as that's
|
| 628 |
+
#probably not what was intended by the user.
|
| 629 |
+
#for log in existing:
|
| 630 |
+
# logger = root.manager.loggerDict[log]
|
| 631 |
+
# if log in child_loggers:
|
| 632 |
+
# logger.level = logging.NOTSET
|
| 633 |
+
# logger.handlers = []
|
| 634 |
+
# logger.propagate = True
|
| 635 |
+
# elif disable_existing:
|
| 636 |
+
# logger.disabled = True
|
| 637 |
+
_handle_existing_loggers(existing, child_loggers,
|
| 638 |
+
disable_existing)
|
| 639 |
+
|
| 640 |
+
# And finally, do the root logger
|
| 641 |
+
root = config.get('root', None)
|
| 642 |
+
if root:
|
| 643 |
+
try:
|
| 644 |
+
self.configure_root(root)
|
| 645 |
+
except Exception as e:
|
| 646 |
+
raise ValueError('Unable to configure root '
|
| 647 |
+
'logger') from e
|
| 648 |
+
finally:
|
| 649 |
+
logging._releaseLock()
|
| 650 |
+
|
| 651 |
+
def configure_formatter(self, config):
|
| 652 |
+
"""Configure a formatter from a dictionary."""
|
| 653 |
+
if '()' in config:
|
| 654 |
+
factory = config['()'] # for use in exception handler
|
| 655 |
+
try:
|
| 656 |
+
result = self.configure_custom(config)
|
| 657 |
+
except TypeError as te:
|
| 658 |
+
if "'format'" not in str(te):
|
| 659 |
+
raise
|
| 660 |
+
#Name of parameter changed from fmt to format.
|
| 661 |
+
#Retry with old name.
|
| 662 |
+
#This is so that code can be used with older Python versions
|
| 663 |
+
#(e.g. by Django)
|
| 664 |
+
config['fmt'] = config.pop('format')
|
| 665 |
+
config['()'] = factory
|
| 666 |
+
result = self.configure_custom(config)
|
| 667 |
+
else:
|
| 668 |
+
fmt = config.get('format', None)
|
| 669 |
+
dfmt = config.get('datefmt', None)
|
| 670 |
+
style = config.get('style', '%')
|
| 671 |
+
cname = config.get('class', None)
|
| 672 |
+
|
| 673 |
+
if not cname:
|
| 674 |
+
c = logging.Formatter
|
| 675 |
+
else:
|
| 676 |
+
c = _resolve(cname)
|
| 677 |
+
|
| 678 |
+
# A TypeError would be raised if "validate" key is passed in with a formatter callable
|
| 679 |
+
# that does not accept "validate" as a parameter
|
| 680 |
+
if 'validate' in config: # if user hasn't mentioned it, the default will be fine
|
| 681 |
+
result = c(fmt, dfmt, style, config['validate'])
|
| 682 |
+
else:
|
| 683 |
+
result = c(fmt, dfmt, style)
|
| 684 |
+
|
| 685 |
+
return result
|
| 686 |
+
|
| 687 |
+
def configure_filter(self, config):
|
| 688 |
+
"""Configure a filter from a dictionary."""
|
| 689 |
+
if '()' in config:
|
| 690 |
+
result = self.configure_custom(config)
|
| 691 |
+
else:
|
| 692 |
+
name = config.get('name', '')
|
| 693 |
+
result = logging.Filter(name)
|
| 694 |
+
return result
|
| 695 |
+
|
| 696 |
+
def add_filters(self, filterer, filters):
|
| 697 |
+
"""Add filters to a filterer from a list of names."""
|
| 698 |
+
for f in filters:
|
| 699 |
+
try:
|
| 700 |
+
filterer.addFilter(self.config['filters'][f])
|
| 701 |
+
except Exception as e:
|
| 702 |
+
raise ValueError('Unable to add filter %r' % f) from e
|
| 703 |
+
|
| 704 |
+
def configure_handler(self, config):
|
| 705 |
+
"""Configure a handler from a dictionary."""
|
| 706 |
+
config_copy = dict(config) # for restoring in case of error
|
| 707 |
+
formatter = config.pop('formatter', None)
|
| 708 |
+
if formatter:
|
| 709 |
+
try:
|
| 710 |
+
formatter = self.config['formatters'][formatter]
|
| 711 |
+
except Exception as e:
|
| 712 |
+
raise ValueError('Unable to set formatter '
|
| 713 |
+
'%r' % formatter) from e
|
| 714 |
+
level = config.pop('level', None)
|
| 715 |
+
filters = config.pop('filters', None)
|
| 716 |
+
if '()' in config:
|
| 717 |
+
c = config.pop('()')
|
| 718 |
+
if not callable(c):
|
| 719 |
+
c = self.resolve(c)
|
| 720 |
+
factory = c
|
| 721 |
+
else:
|
| 722 |
+
cname = config.pop('class')
|
| 723 |
+
klass = self.resolve(cname)
|
| 724 |
+
#Special case for handler which refers to another handler
|
| 725 |
+
if issubclass(klass, logging.handlers.MemoryHandler) and\
|
| 726 |
+
'target' in config:
|
| 727 |
+
try:
|
| 728 |
+
th = self.config['handlers'][config['target']]
|
| 729 |
+
if not isinstance(th, logging.Handler):
|
| 730 |
+
config.update(config_copy) # restore for deferred cfg
|
| 731 |
+
raise TypeError('target not configured yet')
|
| 732 |
+
config['target'] = th
|
| 733 |
+
except Exception as e:
|
| 734 |
+
raise ValueError('Unable to set target handler '
|
| 735 |
+
'%r' % config['target']) from e
|
| 736 |
+
elif issubclass(klass, logging.handlers.SMTPHandler) and\
|
| 737 |
+
'mailhost' in config:
|
| 738 |
+
config['mailhost'] = self.as_tuple(config['mailhost'])
|
| 739 |
+
elif issubclass(klass, logging.handlers.SysLogHandler) and\
|
| 740 |
+
'address' in config:
|
| 741 |
+
config['address'] = self.as_tuple(config['address'])
|
| 742 |
+
factory = klass
|
| 743 |
+
props = config.pop('.', None)
|
| 744 |
+
kwargs = {k: config[k] for k in config if valid_ident(k)}
|
| 745 |
+
try:
|
| 746 |
+
result = factory(**kwargs)
|
| 747 |
+
except TypeError as te:
|
| 748 |
+
if "'stream'" not in str(te):
|
| 749 |
+
raise
|
| 750 |
+
#The argument name changed from strm to stream
|
| 751 |
+
#Retry with old name.
|
| 752 |
+
#This is so that code can be used with older Python versions
|
| 753 |
+
#(e.g. by Django)
|
| 754 |
+
kwargs['strm'] = kwargs.pop('stream')
|
| 755 |
+
result = factory(**kwargs)
|
| 756 |
+
if formatter:
|
| 757 |
+
result.setFormatter(formatter)
|
| 758 |
+
if level is not None:
|
| 759 |
+
result.setLevel(logging._checkLevel(level))
|
| 760 |
+
if filters:
|
| 761 |
+
self.add_filters(result, filters)
|
| 762 |
+
if props:
|
| 763 |
+
for name, value in props.items():
|
| 764 |
+
setattr(result, name, value)
|
| 765 |
+
return result
|
| 766 |
+
|
| 767 |
+
def add_handlers(self, logger, handlers):
|
| 768 |
+
"""Add handlers to a logger from a list of names."""
|
| 769 |
+
for h in handlers:
|
| 770 |
+
try:
|
| 771 |
+
logger.addHandler(self.config['handlers'][h])
|
| 772 |
+
except Exception as e:
|
| 773 |
+
raise ValueError('Unable to add handler %r' % h) from e
|
| 774 |
+
|
| 775 |
+
def common_logger_config(self, logger, config, incremental=False):
|
| 776 |
+
"""
|
| 777 |
+
Perform configuration which is common to root and non-root loggers.
|
| 778 |
+
"""
|
| 779 |
+
level = config.get('level', None)
|
| 780 |
+
if level is not None:
|
| 781 |
+
logger.setLevel(logging._checkLevel(level))
|
| 782 |
+
if not incremental:
|
| 783 |
+
#Remove any existing handlers
|
| 784 |
+
for h in logger.handlers[:]:
|
| 785 |
+
logger.removeHandler(h)
|
| 786 |
+
handlers = config.get('handlers', None)
|
| 787 |
+
if handlers:
|
| 788 |
+
self.add_handlers(logger, handlers)
|
| 789 |
+
filters = config.get('filters', None)
|
| 790 |
+
if filters:
|
| 791 |
+
self.add_filters(logger, filters)
|
| 792 |
+
|
| 793 |
+
def configure_logger(self, name, config, incremental=False):
|
| 794 |
+
"""Configure a non-root logger from a dictionary."""
|
| 795 |
+
logger = logging.getLogger(name)
|
| 796 |
+
self.common_logger_config(logger, config, incremental)
|
| 797 |
+
logger.disabled = False
|
| 798 |
+
propagate = config.get('propagate', None)
|
| 799 |
+
if propagate is not None:
|
| 800 |
+
logger.propagate = propagate
|
| 801 |
+
|
| 802 |
+
def configure_root(self, config, incremental=False):
|
| 803 |
+
"""Configure a root logger from a dictionary."""
|
| 804 |
+
root = logging.getLogger()
|
| 805 |
+
self.common_logger_config(root, config, incremental)
|
| 806 |
+
|
| 807 |
+
dictConfigClass = DictConfigurator
|
| 808 |
+
|
| 809 |
+
def dictConfig(config):
|
| 810 |
+
"""Configure logging using a dictionary."""
|
| 811 |
+
dictConfigClass(config).configure()
|
| 812 |
+
|
| 813 |
+
|
| 814 |
+
def listen(port=DEFAULT_LOGGING_CONFIG_PORT, verify=None):
|
| 815 |
+
"""
|
| 816 |
+
Start up a socket server on the specified port, and listen for new
|
| 817 |
+
configurations.
|
| 818 |
+
|
| 819 |
+
These will be sent as a file suitable for processing by fileConfig().
|
| 820 |
+
Returns a Thread object on which you can call start() to start the server,
|
| 821 |
+
and which you can join() when appropriate. To stop the server, call
|
| 822 |
+
stopListening().
|
| 823 |
+
|
| 824 |
+
Use the ``verify`` argument to verify any bytes received across the wire
|
| 825 |
+
from a client. If specified, it should be a callable which receives a
|
| 826 |
+
single argument - the bytes of configuration data received across the
|
| 827 |
+
network - and it should return either ``None``, to indicate that the
|
| 828 |
+
passed in bytes could not be verified and should be discarded, or a
|
| 829 |
+
byte string which is then passed to the configuration machinery as
|
| 830 |
+
normal. Note that you can return transformed bytes, e.g. by decrypting
|
| 831 |
+
the bytes passed in.
|
| 832 |
+
"""
|
| 833 |
+
|
| 834 |
+
class ConfigStreamHandler(StreamRequestHandler):
|
| 835 |
+
"""
|
| 836 |
+
Handler for a logging configuration request.
|
| 837 |
+
|
| 838 |
+
It expects a completely new logging configuration and uses fileConfig
|
| 839 |
+
to install it.
|
| 840 |
+
"""
|
| 841 |
+
def handle(self):
|
| 842 |
+
"""
|
| 843 |
+
Handle a request.
|
| 844 |
+
|
| 845 |
+
Each request is expected to be a 4-byte length, packed using
|
| 846 |
+
struct.pack(">L", n), followed by the config file.
|
| 847 |
+
Uses fileConfig() to do the grunt work.
|
| 848 |
+
"""
|
| 849 |
+
try:
|
| 850 |
+
conn = self.connection
|
| 851 |
+
chunk = conn.recv(4)
|
| 852 |
+
if len(chunk) == 4:
|
| 853 |
+
slen = struct.unpack(">L", chunk)[0]
|
| 854 |
+
chunk = self.connection.recv(slen)
|
| 855 |
+
while len(chunk) < slen:
|
| 856 |
+
chunk = chunk + conn.recv(slen - len(chunk))
|
| 857 |
+
if self.server.verify is not None:
|
| 858 |
+
chunk = self.server.verify(chunk)
|
| 859 |
+
if chunk is not None: # verified, can process
|
| 860 |
+
chunk = chunk.decode("utf-8")
|
| 861 |
+
try:
|
| 862 |
+
import json
|
| 863 |
+
d =json.loads(chunk)
|
| 864 |
+
assert isinstance(d, dict)
|
| 865 |
+
dictConfig(d)
|
| 866 |
+
except Exception:
|
| 867 |
+
#Apply new configuration.
|
| 868 |
+
|
| 869 |
+
file = io.StringIO(chunk)
|
| 870 |
+
try:
|
| 871 |
+
fileConfig(file)
|
| 872 |
+
except Exception:
|
| 873 |
+
traceback.print_exc()
|
| 874 |
+
if self.server.ready:
|
| 875 |
+
self.server.ready.set()
|
| 876 |
+
except OSError as e:
|
| 877 |
+
if e.errno != RESET_ERROR:
|
| 878 |
+
raise
|
| 879 |
+
|
| 880 |
+
class ConfigSocketReceiver(ThreadingTCPServer):
|
| 881 |
+
"""
|
| 882 |
+
A simple TCP socket-based logging config receiver.
|
| 883 |
+
"""
|
| 884 |
+
|
| 885 |
+
allow_reuse_address = 1
|
| 886 |
+
|
| 887 |
+
def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
|
| 888 |
+
handler=None, ready=None, verify=None):
|
| 889 |
+
ThreadingTCPServer.__init__(self, (host, port), handler)
|
| 890 |
+
logging._acquireLock()
|
| 891 |
+
self.abort = 0
|
| 892 |
+
logging._releaseLock()
|
| 893 |
+
self.timeout = 1
|
| 894 |
+
self.ready = ready
|
| 895 |
+
self.verify = verify
|
| 896 |
+
|
| 897 |
+
def serve_until_stopped(self):
|
| 898 |
+
import select
|
| 899 |
+
abort = 0
|
| 900 |
+
while not abort:
|
| 901 |
+
rd, wr, ex = select.select([self.socket.fileno()],
|
| 902 |
+
[], [],
|
| 903 |
+
self.timeout)
|
| 904 |
+
if rd:
|
| 905 |
+
self.handle_request()
|
| 906 |
+
logging._acquireLock()
|
| 907 |
+
abort = self.abort
|
| 908 |
+
logging._releaseLock()
|
| 909 |
+
self.server_close()
|
| 910 |
+
|
| 911 |
+
class Server(threading.Thread):
|
| 912 |
+
|
| 913 |
+
def __init__(self, rcvr, hdlr, port, verify):
|
| 914 |
+
super(Server, self).__init__()
|
| 915 |
+
self.rcvr = rcvr
|
| 916 |
+
self.hdlr = hdlr
|
| 917 |
+
self.port = port
|
| 918 |
+
self.verify = verify
|
| 919 |
+
self.ready = threading.Event()
|
| 920 |
+
|
| 921 |
+
def run(self):
|
| 922 |
+
server = self.rcvr(port=self.port, handler=self.hdlr,
|
| 923 |
+
ready=self.ready,
|
| 924 |
+
verify=self.verify)
|
| 925 |
+
if self.port == 0:
|
| 926 |
+
self.port = server.server_address[1]
|
| 927 |
+
self.ready.set()
|
| 928 |
+
global _listener
|
| 929 |
+
logging._acquireLock()
|
| 930 |
+
_listener = server
|
| 931 |
+
logging._releaseLock()
|
| 932 |
+
server.serve_until_stopped()
|
| 933 |
+
|
| 934 |
+
return Server(ConfigSocketReceiver, ConfigStreamHandler, port, verify)
|
| 935 |
+
|
| 936 |
+
def stopListening():
|
| 937 |
+
"""
|
| 938 |
+
Stop the listening server which was created with a call to listen().
|
| 939 |
+
"""
|
| 940 |
+
global _listener
|
| 941 |
+
logging._acquireLock()
|
| 942 |
+
try:
|
| 943 |
+
if _listener:
|
| 944 |
+
_listener.abort = 1
|
| 945 |
+
_listener = None
|
| 946 |
+
finally:
|
| 947 |
+
logging._releaseLock()
|
miniconda3/envs/ladir/lib/python3.10/logging/handlers.py
ADDED
|
@@ -0,0 +1,1587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2001-2021 by Vinay Sajip. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Permission to use, copy, modify, and distribute this software and its
|
| 4 |
+
# documentation for any purpose and without fee is hereby granted,
|
| 5 |
+
# provided that the above copyright notice appear in all copies and that
|
| 6 |
+
# both that copyright notice and this permission notice appear in
|
| 7 |
+
# supporting documentation, and that the name of Vinay Sajip
|
| 8 |
+
# not be used in advertising or publicity pertaining to distribution
|
| 9 |
+
# of the software without specific, written prior permission.
|
| 10 |
+
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
|
| 11 |
+
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
|
| 12 |
+
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
|
| 13 |
+
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
|
| 14 |
+
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 15 |
+
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 16 |
+
|
| 17 |
+
"""
|
| 18 |
+
Additional handlers for the logging package for Python. The core package is
|
| 19 |
+
based on PEP 282 and comments thereto in comp.lang.python.
|
| 20 |
+
|
| 21 |
+
Copyright (C) 2001-2021 Vinay Sajip. All Rights Reserved.
|
| 22 |
+
|
| 23 |
+
To use, simply 'import logging.handlers' and log away!
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
import io, logging, socket, os, pickle, struct, time, re
|
| 27 |
+
from stat import ST_DEV, ST_INO, ST_MTIME
|
| 28 |
+
import queue
|
| 29 |
+
import threading
|
| 30 |
+
import copy
|
| 31 |
+
|
| 32 |
+
#
|
| 33 |
+
# Some constants...
|
| 34 |
+
#
|
| 35 |
+
|
| 36 |
+
DEFAULT_TCP_LOGGING_PORT = 9020
|
| 37 |
+
DEFAULT_UDP_LOGGING_PORT = 9021
|
| 38 |
+
DEFAULT_HTTP_LOGGING_PORT = 9022
|
| 39 |
+
DEFAULT_SOAP_LOGGING_PORT = 9023
|
| 40 |
+
SYSLOG_UDP_PORT = 514
|
| 41 |
+
SYSLOG_TCP_PORT = 514
|
| 42 |
+
|
| 43 |
+
_MIDNIGHT = 24 * 60 * 60 # number of seconds in a day
|
| 44 |
+
|
| 45 |
+
class BaseRotatingHandler(logging.FileHandler):
|
| 46 |
+
"""
|
| 47 |
+
Base class for handlers that rotate log files at a certain point.
|
| 48 |
+
Not meant to be instantiated directly. Instead, use RotatingFileHandler
|
| 49 |
+
or TimedRotatingFileHandler.
|
| 50 |
+
"""
|
| 51 |
+
namer = None
|
| 52 |
+
rotator = None
|
| 53 |
+
|
| 54 |
+
def __init__(self, filename, mode, encoding=None, delay=False, errors=None):
|
| 55 |
+
"""
|
| 56 |
+
Use the specified filename for streamed logging
|
| 57 |
+
"""
|
| 58 |
+
logging.FileHandler.__init__(self, filename, mode=mode,
|
| 59 |
+
encoding=encoding, delay=delay,
|
| 60 |
+
errors=errors)
|
| 61 |
+
self.mode = mode
|
| 62 |
+
self.encoding = encoding
|
| 63 |
+
self.errors = errors
|
| 64 |
+
|
| 65 |
+
def emit(self, record):
|
| 66 |
+
"""
|
| 67 |
+
Emit a record.
|
| 68 |
+
|
| 69 |
+
Output the record to the file, catering for rollover as described
|
| 70 |
+
in doRollover().
|
| 71 |
+
"""
|
| 72 |
+
try:
|
| 73 |
+
if self.shouldRollover(record):
|
| 74 |
+
self.doRollover()
|
| 75 |
+
logging.FileHandler.emit(self, record)
|
| 76 |
+
except Exception:
|
| 77 |
+
self.handleError(record)
|
| 78 |
+
|
| 79 |
+
def rotation_filename(self, default_name):
|
| 80 |
+
"""
|
| 81 |
+
Modify the filename of a log file when rotating.
|
| 82 |
+
|
| 83 |
+
This is provided so that a custom filename can be provided.
|
| 84 |
+
|
| 85 |
+
The default implementation calls the 'namer' attribute of the
|
| 86 |
+
handler, if it's callable, passing the default name to
|
| 87 |
+
it. If the attribute isn't callable (the default is None), the name
|
| 88 |
+
is returned unchanged.
|
| 89 |
+
|
| 90 |
+
:param default_name: The default name for the log file.
|
| 91 |
+
"""
|
| 92 |
+
if not callable(self.namer):
|
| 93 |
+
result = default_name
|
| 94 |
+
else:
|
| 95 |
+
result = self.namer(default_name)
|
| 96 |
+
return result
|
| 97 |
+
|
| 98 |
+
def rotate(self, source, dest):
|
| 99 |
+
"""
|
| 100 |
+
When rotating, rotate the current log.
|
| 101 |
+
|
| 102 |
+
The default implementation calls the 'rotator' attribute of the
|
| 103 |
+
handler, if it's callable, passing the source and dest arguments to
|
| 104 |
+
it. If the attribute isn't callable (the default is None), the source
|
| 105 |
+
is simply renamed to the destination.
|
| 106 |
+
|
| 107 |
+
:param source: The source filename. This is normally the base
|
| 108 |
+
filename, e.g. 'test.log'
|
| 109 |
+
:param dest: The destination filename. This is normally
|
| 110 |
+
what the source is rotated to, e.g. 'test.log.1'.
|
| 111 |
+
"""
|
| 112 |
+
if not callable(self.rotator):
|
| 113 |
+
# Issue 18940: A file may not have been created if delay is True.
|
| 114 |
+
if os.path.exists(source):
|
| 115 |
+
os.rename(source, dest)
|
| 116 |
+
else:
|
| 117 |
+
self.rotator(source, dest)
|
| 118 |
+
|
| 119 |
+
class RotatingFileHandler(BaseRotatingHandler):
|
| 120 |
+
"""
|
| 121 |
+
Handler for logging to a set of files, which switches from one file
|
| 122 |
+
to the next when the current file reaches a certain size.
|
| 123 |
+
"""
|
| 124 |
+
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0,
|
| 125 |
+
encoding=None, delay=False, errors=None):
|
| 126 |
+
"""
|
| 127 |
+
Open the specified file and use it as the stream for logging.
|
| 128 |
+
|
| 129 |
+
By default, the file grows indefinitely. You can specify particular
|
| 130 |
+
values of maxBytes and backupCount to allow the file to rollover at
|
| 131 |
+
a predetermined size.
|
| 132 |
+
|
| 133 |
+
Rollover occurs whenever the current log file is nearly maxBytes in
|
| 134 |
+
length. If backupCount is >= 1, the system will successively create
|
| 135 |
+
new files with the same pathname as the base file, but with extensions
|
| 136 |
+
".1", ".2" etc. appended to it. For example, with a backupCount of 5
|
| 137 |
+
and a base file name of "app.log", you would get "app.log",
|
| 138 |
+
"app.log.1", "app.log.2", ... through to "app.log.5". The file being
|
| 139 |
+
written to is always "app.log" - when it gets filled up, it is closed
|
| 140 |
+
and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
|
| 141 |
+
exist, then they are renamed to "app.log.2", "app.log.3" etc.
|
| 142 |
+
respectively.
|
| 143 |
+
|
| 144 |
+
If maxBytes is zero, rollover never occurs.
|
| 145 |
+
"""
|
| 146 |
+
# If rotation/rollover is wanted, it doesn't make sense to use another
|
| 147 |
+
# mode. If for example 'w' were specified, then if there were multiple
|
| 148 |
+
# runs of the calling application, the logs from previous runs would be
|
| 149 |
+
# lost if the 'w' is respected, because the log file would be truncated
|
| 150 |
+
# on each run.
|
| 151 |
+
if maxBytes > 0:
|
| 152 |
+
mode = 'a'
|
| 153 |
+
if "b" not in mode:
|
| 154 |
+
encoding = io.text_encoding(encoding)
|
| 155 |
+
BaseRotatingHandler.__init__(self, filename, mode, encoding=encoding,
|
| 156 |
+
delay=delay, errors=errors)
|
| 157 |
+
self.maxBytes = maxBytes
|
| 158 |
+
self.backupCount = backupCount
|
| 159 |
+
|
| 160 |
+
def doRollover(self):
|
| 161 |
+
"""
|
| 162 |
+
Do a rollover, as described in __init__().
|
| 163 |
+
"""
|
| 164 |
+
if self.stream:
|
| 165 |
+
self.stream.close()
|
| 166 |
+
self.stream = None
|
| 167 |
+
if self.backupCount > 0:
|
| 168 |
+
for i in range(self.backupCount - 1, 0, -1):
|
| 169 |
+
sfn = self.rotation_filename("%s.%d" % (self.baseFilename, i))
|
| 170 |
+
dfn = self.rotation_filename("%s.%d" % (self.baseFilename,
|
| 171 |
+
i + 1))
|
| 172 |
+
if os.path.exists(sfn):
|
| 173 |
+
if os.path.exists(dfn):
|
| 174 |
+
os.remove(dfn)
|
| 175 |
+
os.rename(sfn, dfn)
|
| 176 |
+
dfn = self.rotation_filename(self.baseFilename + ".1")
|
| 177 |
+
if os.path.exists(dfn):
|
| 178 |
+
os.remove(dfn)
|
| 179 |
+
self.rotate(self.baseFilename, dfn)
|
| 180 |
+
if not self.delay:
|
| 181 |
+
self.stream = self._open()
|
| 182 |
+
|
| 183 |
+
def shouldRollover(self, record):
|
| 184 |
+
"""
|
| 185 |
+
Determine if rollover should occur.
|
| 186 |
+
|
| 187 |
+
Basically, see if the supplied record would cause the file to exceed
|
| 188 |
+
the size limit we have.
|
| 189 |
+
"""
|
| 190 |
+
# See bpo-45401: Never rollover anything other than regular files
|
| 191 |
+
if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename):
|
| 192 |
+
return False
|
| 193 |
+
if self.stream is None: # delay was set...
|
| 194 |
+
self.stream = self._open()
|
| 195 |
+
if self.maxBytes > 0: # are we rolling over?
|
| 196 |
+
msg = "%s\n" % self.format(record)
|
| 197 |
+
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
|
| 198 |
+
if self.stream.tell() + len(msg) >= self.maxBytes:
|
| 199 |
+
return True
|
| 200 |
+
return False
|
| 201 |
+
|
| 202 |
+
class TimedRotatingFileHandler(BaseRotatingHandler):
|
| 203 |
+
"""
|
| 204 |
+
Handler for logging to a file, rotating the log file at certain timed
|
| 205 |
+
intervals.
|
| 206 |
+
|
| 207 |
+
If backupCount is > 0, when rollover is done, no more than backupCount
|
| 208 |
+
files are kept - the oldest ones are deleted.
|
| 209 |
+
"""
|
| 210 |
+
def __init__(self, filename, when='h', interval=1, backupCount=0,
|
| 211 |
+
encoding=None, delay=False, utc=False, atTime=None,
|
| 212 |
+
errors=None):
|
| 213 |
+
encoding = io.text_encoding(encoding)
|
| 214 |
+
BaseRotatingHandler.__init__(self, filename, 'a', encoding=encoding,
|
| 215 |
+
delay=delay, errors=errors)
|
| 216 |
+
self.when = when.upper()
|
| 217 |
+
self.backupCount = backupCount
|
| 218 |
+
self.utc = utc
|
| 219 |
+
self.atTime = atTime
|
| 220 |
+
# Calculate the real rollover interval, which is just the number of
|
| 221 |
+
# seconds between rollovers. Also set the filename suffix used when
|
| 222 |
+
# a rollover occurs. Current 'when' events supported:
|
| 223 |
+
# S - Seconds
|
| 224 |
+
# M - Minutes
|
| 225 |
+
# H - Hours
|
| 226 |
+
# D - Days
|
| 227 |
+
# midnight - roll over at midnight
|
| 228 |
+
# W{0-6} - roll over on a certain day; 0 - Monday
|
| 229 |
+
#
|
| 230 |
+
# Case of the 'when' specifier is not important; lower or upper case
|
| 231 |
+
# will work.
|
| 232 |
+
if self.when == 'S':
|
| 233 |
+
self.interval = 1 # one second
|
| 234 |
+
self.suffix = "%Y-%m-%d_%H-%M-%S"
|
| 235 |
+
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}(\.\w+)?$"
|
| 236 |
+
elif self.when == 'M':
|
| 237 |
+
self.interval = 60 # one minute
|
| 238 |
+
self.suffix = "%Y-%m-%d_%H-%M"
|
| 239 |
+
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}(\.\w+)?$"
|
| 240 |
+
elif self.when == 'H':
|
| 241 |
+
self.interval = 60 * 60 # one hour
|
| 242 |
+
self.suffix = "%Y-%m-%d_%H"
|
| 243 |
+
self.extMatch = r"^\d{4}-\d{2}-\d{2}_\d{2}(\.\w+)?$"
|
| 244 |
+
elif self.when == 'D' or self.when == 'MIDNIGHT':
|
| 245 |
+
self.interval = 60 * 60 * 24 # one day
|
| 246 |
+
self.suffix = "%Y-%m-%d"
|
| 247 |
+
self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
|
| 248 |
+
elif self.when.startswith('W'):
|
| 249 |
+
self.interval = 60 * 60 * 24 * 7 # one week
|
| 250 |
+
if len(self.when) != 2:
|
| 251 |
+
raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
|
| 252 |
+
if self.when[1] < '0' or self.when[1] > '6':
|
| 253 |
+
raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
|
| 254 |
+
self.dayOfWeek = int(self.when[1])
|
| 255 |
+
self.suffix = "%Y-%m-%d"
|
| 256 |
+
self.extMatch = r"^\d{4}-\d{2}-\d{2}(\.\w+)?$"
|
| 257 |
+
else:
|
| 258 |
+
raise ValueError("Invalid rollover interval specified: %s" % self.when)
|
| 259 |
+
|
| 260 |
+
self.extMatch = re.compile(self.extMatch, re.ASCII)
|
| 261 |
+
self.interval = self.interval * interval # multiply by units requested
|
| 262 |
+
# The following line added because the filename passed in could be a
|
| 263 |
+
# path object (see Issue #27493), but self.baseFilename will be a string
|
| 264 |
+
filename = self.baseFilename
|
| 265 |
+
if os.path.exists(filename):
|
| 266 |
+
t = os.stat(filename)[ST_MTIME]
|
| 267 |
+
else:
|
| 268 |
+
t = int(time.time())
|
| 269 |
+
self.rolloverAt = self.computeRollover(t)
|
| 270 |
+
|
| 271 |
+
def computeRollover(self, currentTime):
|
| 272 |
+
"""
|
| 273 |
+
Work out the rollover time based on the specified time.
|
| 274 |
+
"""
|
| 275 |
+
result = currentTime + self.interval
|
| 276 |
+
# If we are rolling over at midnight or weekly, then the interval is already known.
|
| 277 |
+
# What we need to figure out is WHEN the next interval is. In other words,
|
| 278 |
+
# if you are rolling over at midnight, then your base interval is 1 day,
|
| 279 |
+
# but you want to start that one day clock at midnight, not now. So, we
|
| 280 |
+
# have to fudge the rolloverAt value in order to trigger the first rollover
|
| 281 |
+
# at the right time. After that, the regular interval will take care of
|
| 282 |
+
# the rest. Note that this code doesn't care about leap seconds. :)
|
| 283 |
+
if self.when == 'MIDNIGHT' or self.when.startswith('W'):
|
| 284 |
+
# This could be done with less code, but I wanted it to be clear
|
| 285 |
+
if self.utc:
|
| 286 |
+
t = time.gmtime(currentTime)
|
| 287 |
+
else:
|
| 288 |
+
t = time.localtime(currentTime)
|
| 289 |
+
currentHour = t[3]
|
| 290 |
+
currentMinute = t[4]
|
| 291 |
+
currentSecond = t[5]
|
| 292 |
+
currentDay = t[6]
|
| 293 |
+
# r is the number of seconds left between now and the next rotation
|
| 294 |
+
if self.atTime is None:
|
| 295 |
+
rotate_ts = _MIDNIGHT
|
| 296 |
+
else:
|
| 297 |
+
rotate_ts = ((self.atTime.hour * 60 + self.atTime.minute)*60 +
|
| 298 |
+
self.atTime.second)
|
| 299 |
+
|
| 300 |
+
r = rotate_ts - ((currentHour * 60 + currentMinute) * 60 +
|
| 301 |
+
currentSecond)
|
| 302 |
+
if r < 0:
|
| 303 |
+
# Rotate time is before the current time (for example when
|
| 304 |
+
# self.rotateAt is 13:45 and it now 14:15), rotation is
|
| 305 |
+
# tomorrow.
|
| 306 |
+
r += _MIDNIGHT
|
| 307 |
+
currentDay = (currentDay + 1) % 7
|
| 308 |
+
result = currentTime + r
|
| 309 |
+
# If we are rolling over on a certain day, add in the number of days until
|
| 310 |
+
# the next rollover, but offset by 1 since we just calculated the time
|
| 311 |
+
# until the next day starts. There are three cases:
|
| 312 |
+
# Case 1) The day to rollover is today; in this case, do nothing
|
| 313 |
+
# Case 2) The day to rollover is further in the interval (i.e., today is
|
| 314 |
+
# day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
|
| 315 |
+
# next rollover is simply 6 - 2 - 1, or 3.
|
| 316 |
+
# Case 3) The day to rollover is behind us in the interval (i.e., today
|
| 317 |
+
# is day 5 (Saturday) and rollover is on day 3 (Thursday).
|
| 318 |
+
# Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
|
| 319 |
+
# number of days left in the current week (1) plus the number
|
| 320 |
+
# of days in the next week until the rollover day (3).
|
| 321 |
+
# The calculations described in 2) and 3) above need to have a day added.
|
| 322 |
+
# This is because the above time calculation takes us to midnight on this
|
| 323 |
+
# day, i.e. the start of the next day.
|
| 324 |
+
if self.when.startswith('W'):
|
| 325 |
+
day = currentDay # 0 is Monday
|
| 326 |
+
if day != self.dayOfWeek:
|
| 327 |
+
if day < self.dayOfWeek:
|
| 328 |
+
daysToWait = self.dayOfWeek - day
|
| 329 |
+
else:
|
| 330 |
+
daysToWait = 6 - day + self.dayOfWeek + 1
|
| 331 |
+
newRolloverAt = result + (daysToWait * (60 * 60 * 24))
|
| 332 |
+
if not self.utc:
|
| 333 |
+
dstNow = t[-1]
|
| 334 |
+
dstAtRollover = time.localtime(newRolloverAt)[-1]
|
| 335 |
+
if dstNow != dstAtRollover:
|
| 336 |
+
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
|
| 337 |
+
addend = -3600
|
| 338 |
+
else: # DST bows out before next rollover, so we need to add an hour
|
| 339 |
+
addend = 3600
|
| 340 |
+
newRolloverAt += addend
|
| 341 |
+
result = newRolloverAt
|
| 342 |
+
return result
|
| 343 |
+
|
| 344 |
+
def shouldRollover(self, record):
|
| 345 |
+
"""
|
| 346 |
+
Determine if rollover should occur.
|
| 347 |
+
|
| 348 |
+
record is not used, as we are just comparing times, but it is needed so
|
| 349 |
+
the method signatures are the same
|
| 350 |
+
"""
|
| 351 |
+
t = int(time.time())
|
| 352 |
+
if t >= self.rolloverAt:
|
| 353 |
+
# See #89564: Never rollover anything other than regular files
|
| 354 |
+
if os.path.exists(self.baseFilename) and not os.path.isfile(self.baseFilename):
|
| 355 |
+
# The file is not a regular file, so do not rollover, but do
|
| 356 |
+
# set the next rollover time to avoid repeated checks.
|
| 357 |
+
self.rolloverAt = self.computeRollover(t)
|
| 358 |
+
return False
|
| 359 |
+
|
| 360 |
+
return True
|
| 361 |
+
return False
|
| 362 |
+
|
| 363 |
+
def getFilesToDelete(self):
|
| 364 |
+
"""
|
| 365 |
+
Determine the files to delete when rolling over.
|
| 366 |
+
|
| 367 |
+
More specific than the earlier method, which just used glob.glob().
|
| 368 |
+
"""
|
| 369 |
+
dirName, baseName = os.path.split(self.baseFilename)
|
| 370 |
+
fileNames = os.listdir(dirName)
|
| 371 |
+
result = []
|
| 372 |
+
# See bpo-44753: Don't use the extension when computing the prefix.
|
| 373 |
+
n, e = os.path.splitext(baseName)
|
| 374 |
+
prefix = n + '.'
|
| 375 |
+
plen = len(prefix)
|
| 376 |
+
for fileName in fileNames:
|
| 377 |
+
if self.namer is None:
|
| 378 |
+
# Our files will always start with baseName
|
| 379 |
+
if not fileName.startswith(baseName):
|
| 380 |
+
continue
|
| 381 |
+
else:
|
| 382 |
+
# Our files could be just about anything after custom naming, but
|
| 383 |
+
# likely candidates are of the form
|
| 384 |
+
# foo.log.DATETIME_SUFFIX or foo.DATETIME_SUFFIX.log
|
| 385 |
+
if (not fileName.startswith(baseName) and fileName.endswith(e) and
|
| 386 |
+
len(fileName) > (plen + 1) and not fileName[plen+1].isdigit()):
|
| 387 |
+
continue
|
| 388 |
+
|
| 389 |
+
if fileName[:plen] == prefix:
|
| 390 |
+
suffix = fileName[plen:]
|
| 391 |
+
# See bpo-45628: The date/time suffix could be anywhere in the
|
| 392 |
+
# filename
|
| 393 |
+
parts = suffix.split('.')
|
| 394 |
+
for part in parts:
|
| 395 |
+
if self.extMatch.match(part):
|
| 396 |
+
result.append(os.path.join(dirName, fileName))
|
| 397 |
+
break
|
| 398 |
+
if len(result) < self.backupCount:
|
| 399 |
+
result = []
|
| 400 |
+
else:
|
| 401 |
+
result.sort()
|
| 402 |
+
result = result[:len(result) - self.backupCount]
|
| 403 |
+
return result
|
| 404 |
+
|
| 405 |
+
def doRollover(self):
|
| 406 |
+
"""
|
| 407 |
+
do a rollover; in this case, a date/time stamp is appended to the filename
|
| 408 |
+
when the rollover happens. However, you want the file to be named for the
|
| 409 |
+
start of the interval, not the current time. If there is a backup count,
|
| 410 |
+
then we have to get a list of matching filenames, sort them and remove
|
| 411 |
+
the one with the oldest suffix.
|
| 412 |
+
"""
|
| 413 |
+
if self.stream:
|
| 414 |
+
self.stream.close()
|
| 415 |
+
self.stream = None
|
| 416 |
+
# get the time that this sequence started at and make it a TimeTuple
|
| 417 |
+
currentTime = int(time.time())
|
| 418 |
+
dstNow = time.localtime(currentTime)[-1]
|
| 419 |
+
t = self.rolloverAt - self.interval
|
| 420 |
+
if self.utc:
|
| 421 |
+
timeTuple = time.gmtime(t)
|
| 422 |
+
else:
|
| 423 |
+
timeTuple = time.localtime(t)
|
| 424 |
+
dstThen = timeTuple[-1]
|
| 425 |
+
if dstNow != dstThen:
|
| 426 |
+
if dstNow:
|
| 427 |
+
addend = 3600
|
| 428 |
+
else:
|
| 429 |
+
addend = -3600
|
| 430 |
+
timeTuple = time.localtime(t + addend)
|
| 431 |
+
dfn = self.rotation_filename(self.baseFilename + "." +
|
| 432 |
+
time.strftime(self.suffix, timeTuple))
|
| 433 |
+
if os.path.exists(dfn):
|
| 434 |
+
os.remove(dfn)
|
| 435 |
+
self.rotate(self.baseFilename, dfn)
|
| 436 |
+
if self.backupCount > 0:
|
| 437 |
+
for s in self.getFilesToDelete():
|
| 438 |
+
os.remove(s)
|
| 439 |
+
if not self.delay:
|
| 440 |
+
self.stream = self._open()
|
| 441 |
+
newRolloverAt = self.computeRollover(currentTime)
|
| 442 |
+
while newRolloverAt <= currentTime:
|
| 443 |
+
newRolloverAt = newRolloverAt + self.interval
|
| 444 |
+
#If DST changes and midnight or weekly rollover, adjust for this.
|
| 445 |
+
if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc:
|
| 446 |
+
dstAtRollover = time.localtime(newRolloverAt)[-1]
|
| 447 |
+
if dstNow != dstAtRollover:
|
| 448 |
+
if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour
|
| 449 |
+
addend = -3600
|
| 450 |
+
else: # DST bows out before next rollover, so we need to add an hour
|
| 451 |
+
addend = 3600
|
| 452 |
+
newRolloverAt += addend
|
| 453 |
+
self.rolloverAt = newRolloverAt
|
| 454 |
+
|
| 455 |
+
class WatchedFileHandler(logging.FileHandler):
|
| 456 |
+
"""
|
| 457 |
+
A handler for logging to a file, which watches the file
|
| 458 |
+
to see if it has changed while in use. This can happen because of
|
| 459 |
+
usage of programs such as newsyslog and logrotate which perform
|
| 460 |
+
log file rotation. This handler, intended for use under Unix,
|
| 461 |
+
watches the file to see if it has changed since the last emit.
|
| 462 |
+
(A file has changed if its device or inode have changed.)
|
| 463 |
+
If it has changed, the old file stream is closed, and the file
|
| 464 |
+
opened to get a new stream.
|
| 465 |
+
|
| 466 |
+
This handler is not appropriate for use under Windows, because
|
| 467 |
+
under Windows open files cannot be moved or renamed - logging
|
| 468 |
+
opens the files with exclusive locks - and so there is no need
|
| 469 |
+
for such a handler. Furthermore, ST_INO is not supported under
|
| 470 |
+
Windows; stat always returns zero for this value.
|
| 471 |
+
|
| 472 |
+
This handler is based on a suggestion and patch by Chad J.
|
| 473 |
+
Schroeder.
|
| 474 |
+
"""
|
| 475 |
+
def __init__(self, filename, mode='a', encoding=None, delay=False,
|
| 476 |
+
errors=None):
|
| 477 |
+
if "b" not in mode:
|
| 478 |
+
encoding = io.text_encoding(encoding)
|
| 479 |
+
logging.FileHandler.__init__(self, filename, mode=mode,
|
| 480 |
+
encoding=encoding, delay=delay,
|
| 481 |
+
errors=errors)
|
| 482 |
+
self.dev, self.ino = -1, -1
|
| 483 |
+
self._statstream()
|
| 484 |
+
|
| 485 |
+
def _statstream(self):
|
| 486 |
+
if self.stream:
|
| 487 |
+
sres = os.fstat(self.stream.fileno())
|
| 488 |
+
self.dev, self.ino = sres[ST_DEV], sres[ST_INO]
|
| 489 |
+
|
| 490 |
+
def reopenIfNeeded(self):
|
| 491 |
+
"""
|
| 492 |
+
Reopen log file if needed.
|
| 493 |
+
|
| 494 |
+
Checks if the underlying file has changed, and if it
|
| 495 |
+
has, close the old stream and reopen the file to get the
|
| 496 |
+
current stream.
|
| 497 |
+
"""
|
| 498 |
+
# Reduce the chance of race conditions by stat'ing by path only
|
| 499 |
+
# once and then fstat'ing our new fd if we opened a new log stream.
|
| 500 |
+
# See issue #14632: Thanks to John Mulligan for the problem report
|
| 501 |
+
# and patch.
|
| 502 |
+
try:
|
| 503 |
+
# stat the file by path, checking for existence
|
| 504 |
+
sres = os.stat(self.baseFilename)
|
| 505 |
+
except FileNotFoundError:
|
| 506 |
+
sres = None
|
| 507 |
+
# compare file system stat with that of our stream file handle
|
| 508 |
+
if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino:
|
| 509 |
+
if self.stream is not None:
|
| 510 |
+
# we have an open file handle, clean it up
|
| 511 |
+
self.stream.flush()
|
| 512 |
+
self.stream.close()
|
| 513 |
+
self.stream = None # See Issue #21742: _open () might fail.
|
| 514 |
+
# open a new file handle and get new stat info from that fd
|
| 515 |
+
self.stream = self._open()
|
| 516 |
+
self._statstream()
|
| 517 |
+
|
| 518 |
+
def emit(self, record):
|
| 519 |
+
"""
|
| 520 |
+
Emit a record.
|
| 521 |
+
|
| 522 |
+
If underlying file has changed, reopen the file before emitting the
|
| 523 |
+
record to it.
|
| 524 |
+
"""
|
| 525 |
+
self.reopenIfNeeded()
|
| 526 |
+
logging.FileHandler.emit(self, record)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
class SocketHandler(logging.Handler):
|
| 530 |
+
"""
|
| 531 |
+
A handler class which writes logging records, in pickle format, to
|
| 532 |
+
a streaming socket. The socket is kept open across logging calls.
|
| 533 |
+
If the peer resets it, an attempt is made to reconnect on the next call.
|
| 534 |
+
The pickle which is sent is that of the LogRecord's attribute dictionary
|
| 535 |
+
(__dict__), so that the receiver does not need to have the logging module
|
| 536 |
+
installed in order to process the logging event.
|
| 537 |
+
|
| 538 |
+
To unpickle the record at the receiving end into a LogRecord, use the
|
| 539 |
+
makeLogRecord function.
|
| 540 |
+
"""
|
| 541 |
+
|
| 542 |
+
def __init__(self, host, port):
|
| 543 |
+
"""
|
| 544 |
+
Initializes the handler with a specific host address and port.
|
| 545 |
+
|
| 546 |
+
When the attribute *closeOnError* is set to True - if a socket error
|
| 547 |
+
occurs, the socket is silently closed and then reopened on the next
|
| 548 |
+
logging call.
|
| 549 |
+
"""
|
| 550 |
+
logging.Handler.__init__(self)
|
| 551 |
+
self.host = host
|
| 552 |
+
self.port = port
|
| 553 |
+
if port is None:
|
| 554 |
+
self.address = host
|
| 555 |
+
else:
|
| 556 |
+
self.address = (host, port)
|
| 557 |
+
self.sock = None
|
| 558 |
+
self.closeOnError = False
|
| 559 |
+
self.retryTime = None
|
| 560 |
+
#
|
| 561 |
+
# Exponential backoff parameters.
|
| 562 |
+
#
|
| 563 |
+
self.retryStart = 1.0
|
| 564 |
+
self.retryMax = 30.0
|
| 565 |
+
self.retryFactor = 2.0
|
| 566 |
+
|
| 567 |
+
def makeSocket(self, timeout=1):
|
| 568 |
+
"""
|
| 569 |
+
A factory method which allows subclasses to define the precise
|
| 570 |
+
type of socket they want.
|
| 571 |
+
"""
|
| 572 |
+
if self.port is not None:
|
| 573 |
+
result = socket.create_connection(self.address, timeout=timeout)
|
| 574 |
+
else:
|
| 575 |
+
result = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
| 576 |
+
result.settimeout(timeout)
|
| 577 |
+
try:
|
| 578 |
+
result.connect(self.address)
|
| 579 |
+
except OSError:
|
| 580 |
+
result.close() # Issue 19182
|
| 581 |
+
raise
|
| 582 |
+
return result
|
| 583 |
+
|
| 584 |
+
def createSocket(self):
|
| 585 |
+
"""
|
| 586 |
+
Try to create a socket, using an exponential backoff with
|
| 587 |
+
a max retry time. Thanks to Robert Olson for the original patch
|
| 588 |
+
(SF #815911) which has been slightly refactored.
|
| 589 |
+
"""
|
| 590 |
+
now = time.time()
|
| 591 |
+
# Either retryTime is None, in which case this
|
| 592 |
+
# is the first time back after a disconnect, or
|
| 593 |
+
# we've waited long enough.
|
| 594 |
+
if self.retryTime is None:
|
| 595 |
+
attempt = True
|
| 596 |
+
else:
|
| 597 |
+
attempt = (now >= self.retryTime)
|
| 598 |
+
if attempt:
|
| 599 |
+
try:
|
| 600 |
+
self.sock = self.makeSocket()
|
| 601 |
+
self.retryTime = None # next time, no delay before trying
|
| 602 |
+
except OSError:
|
| 603 |
+
#Creation failed, so set the retry time and return.
|
| 604 |
+
if self.retryTime is None:
|
| 605 |
+
self.retryPeriod = self.retryStart
|
| 606 |
+
else:
|
| 607 |
+
self.retryPeriod = self.retryPeriod * self.retryFactor
|
| 608 |
+
if self.retryPeriod > self.retryMax:
|
| 609 |
+
self.retryPeriod = self.retryMax
|
| 610 |
+
self.retryTime = now + self.retryPeriod
|
| 611 |
+
|
| 612 |
+
def send(self, s):
|
| 613 |
+
"""
|
| 614 |
+
Send a pickled string to the socket.
|
| 615 |
+
|
| 616 |
+
This function allows for partial sends which can happen when the
|
| 617 |
+
network is busy.
|
| 618 |
+
"""
|
| 619 |
+
if self.sock is None:
|
| 620 |
+
self.createSocket()
|
| 621 |
+
#self.sock can be None either because we haven't reached the retry
|
| 622 |
+
#time yet, or because we have reached the retry time and retried,
|
| 623 |
+
#but are still unable to connect.
|
| 624 |
+
if self.sock:
|
| 625 |
+
try:
|
| 626 |
+
self.sock.sendall(s)
|
| 627 |
+
except OSError: #pragma: no cover
|
| 628 |
+
self.sock.close()
|
| 629 |
+
self.sock = None # so we can call createSocket next time
|
| 630 |
+
|
| 631 |
+
def makePickle(self, record):
|
| 632 |
+
"""
|
| 633 |
+
Pickles the record in binary format with a length prefix, and
|
| 634 |
+
returns it ready for transmission across the socket.
|
| 635 |
+
"""
|
| 636 |
+
ei = record.exc_info
|
| 637 |
+
if ei:
|
| 638 |
+
# just to get traceback text into record.exc_text ...
|
| 639 |
+
dummy = self.format(record)
|
| 640 |
+
# See issue #14436: If msg or args are objects, they may not be
|
| 641 |
+
# available on the receiving end. So we convert the msg % args
|
| 642 |
+
# to a string, save it as msg and zap the args.
|
| 643 |
+
d = dict(record.__dict__)
|
| 644 |
+
d['msg'] = record.getMessage()
|
| 645 |
+
d['args'] = None
|
| 646 |
+
d['exc_info'] = None
|
| 647 |
+
# Issue #25685: delete 'message' if present: redundant with 'msg'
|
| 648 |
+
d.pop('message', None)
|
| 649 |
+
s = pickle.dumps(d, 1)
|
| 650 |
+
slen = struct.pack(">L", len(s))
|
| 651 |
+
return slen + s
|
| 652 |
+
|
| 653 |
+
def handleError(self, record):
|
| 654 |
+
"""
|
| 655 |
+
Handle an error during logging.
|
| 656 |
+
|
| 657 |
+
An error has occurred during logging. Most likely cause -
|
| 658 |
+
connection lost. Close the socket so that we can retry on the
|
| 659 |
+
next event.
|
| 660 |
+
"""
|
| 661 |
+
if self.closeOnError and self.sock:
|
| 662 |
+
self.sock.close()
|
| 663 |
+
self.sock = None #try to reconnect next time
|
| 664 |
+
else:
|
| 665 |
+
logging.Handler.handleError(self, record)
|
| 666 |
+
|
| 667 |
+
def emit(self, record):
|
| 668 |
+
"""
|
| 669 |
+
Emit a record.
|
| 670 |
+
|
| 671 |
+
Pickles the record and writes it to the socket in binary format.
|
| 672 |
+
If there is an error with the socket, silently drop the packet.
|
| 673 |
+
If there was a problem with the socket, re-establishes the
|
| 674 |
+
socket.
|
| 675 |
+
"""
|
| 676 |
+
try:
|
| 677 |
+
s = self.makePickle(record)
|
| 678 |
+
self.send(s)
|
| 679 |
+
except Exception:
|
| 680 |
+
self.handleError(record)
|
| 681 |
+
|
| 682 |
+
def close(self):
|
| 683 |
+
"""
|
| 684 |
+
Closes the socket.
|
| 685 |
+
"""
|
| 686 |
+
self.acquire()
|
| 687 |
+
try:
|
| 688 |
+
sock = self.sock
|
| 689 |
+
if sock:
|
| 690 |
+
self.sock = None
|
| 691 |
+
sock.close()
|
| 692 |
+
logging.Handler.close(self)
|
| 693 |
+
finally:
|
| 694 |
+
self.release()
|
| 695 |
+
|
| 696 |
+
class DatagramHandler(SocketHandler):
|
| 697 |
+
"""
|
| 698 |
+
A handler class which writes logging records, in pickle format, to
|
| 699 |
+
a datagram socket. The pickle which is sent is that of the LogRecord's
|
| 700 |
+
attribute dictionary (__dict__), so that the receiver does not need to
|
| 701 |
+
have the logging module installed in order to process the logging event.
|
| 702 |
+
|
| 703 |
+
To unpickle the record at the receiving end into a LogRecord, use the
|
| 704 |
+
makeLogRecord function.
|
| 705 |
+
|
| 706 |
+
"""
|
| 707 |
+
def __init__(self, host, port):
|
| 708 |
+
"""
|
| 709 |
+
Initializes the handler with a specific host address and port.
|
| 710 |
+
"""
|
| 711 |
+
SocketHandler.__init__(self, host, port)
|
| 712 |
+
self.closeOnError = False
|
| 713 |
+
|
| 714 |
+
def makeSocket(self):
|
| 715 |
+
"""
|
| 716 |
+
The factory method of SocketHandler is here overridden to create
|
| 717 |
+
a UDP socket (SOCK_DGRAM).
|
| 718 |
+
"""
|
| 719 |
+
if self.port is None:
|
| 720 |
+
family = socket.AF_UNIX
|
| 721 |
+
else:
|
| 722 |
+
family = socket.AF_INET
|
| 723 |
+
s = socket.socket(family, socket.SOCK_DGRAM)
|
| 724 |
+
return s
|
| 725 |
+
|
| 726 |
+
def send(self, s):
|
| 727 |
+
"""
|
| 728 |
+
Send a pickled string to a socket.
|
| 729 |
+
|
| 730 |
+
This function no longer allows for partial sends which can happen
|
| 731 |
+
when the network is busy - UDP does not guarantee delivery and
|
| 732 |
+
can deliver packets out of sequence.
|
| 733 |
+
"""
|
| 734 |
+
if self.sock is None:
|
| 735 |
+
self.createSocket()
|
| 736 |
+
self.sock.sendto(s, self.address)
|
| 737 |
+
|
| 738 |
+
class SysLogHandler(logging.Handler):
|
| 739 |
+
"""
|
| 740 |
+
A handler class which sends formatted logging records to a syslog
|
| 741 |
+
server. Based on Sam Rushing's syslog module:
|
| 742 |
+
http://www.nightmare.com/squirl/python-ext/misc/syslog.py
|
| 743 |
+
Contributed by Nicolas Untz (after which minor refactoring changes
|
| 744 |
+
have been made).
|
| 745 |
+
"""
|
| 746 |
+
|
| 747 |
+
# from <linux/sys/syslog.h>:
|
| 748 |
+
# ======================================================================
|
| 749 |
+
# priorities/facilities are encoded into a single 32-bit quantity, where
|
| 750 |
+
# the bottom 3 bits are the priority (0-7) and the top 28 bits are the
|
| 751 |
+
# facility (0-big number). Both the priorities and the facilities map
|
| 752 |
+
# roughly one-to-one to strings in the syslogd(8) source code. This
|
| 753 |
+
# mapping is included in this file.
|
| 754 |
+
#
|
| 755 |
+
# priorities (these are ordered)
|
| 756 |
+
|
| 757 |
+
LOG_EMERG = 0 # system is unusable
|
| 758 |
+
LOG_ALERT = 1 # action must be taken immediately
|
| 759 |
+
LOG_CRIT = 2 # critical conditions
|
| 760 |
+
LOG_ERR = 3 # error conditions
|
| 761 |
+
LOG_WARNING = 4 # warning conditions
|
| 762 |
+
LOG_NOTICE = 5 # normal but significant condition
|
| 763 |
+
LOG_INFO = 6 # informational
|
| 764 |
+
LOG_DEBUG = 7 # debug-level messages
|
| 765 |
+
|
| 766 |
+
# facility codes
|
| 767 |
+
LOG_KERN = 0 # kernel messages
|
| 768 |
+
LOG_USER = 1 # random user-level messages
|
| 769 |
+
LOG_MAIL = 2 # mail system
|
| 770 |
+
LOG_DAEMON = 3 # system daemons
|
| 771 |
+
LOG_AUTH = 4 # security/authorization messages
|
| 772 |
+
LOG_SYSLOG = 5 # messages generated internally by syslogd
|
| 773 |
+
LOG_LPR = 6 # line printer subsystem
|
| 774 |
+
LOG_NEWS = 7 # network news subsystem
|
| 775 |
+
LOG_UUCP = 8 # UUCP subsystem
|
| 776 |
+
LOG_CRON = 9 # clock daemon
|
| 777 |
+
LOG_AUTHPRIV = 10 # security/authorization messages (private)
|
| 778 |
+
LOG_FTP = 11 # FTP daemon
|
| 779 |
+
LOG_NTP = 12 # NTP subsystem
|
| 780 |
+
LOG_SECURITY = 13 # Log audit
|
| 781 |
+
LOG_CONSOLE = 14 # Log alert
|
| 782 |
+
LOG_SOLCRON = 15 # Scheduling daemon (Solaris)
|
| 783 |
+
|
| 784 |
+
# other codes through 15 reserved for system use
|
| 785 |
+
LOG_LOCAL0 = 16 # reserved for local use
|
| 786 |
+
LOG_LOCAL1 = 17 # reserved for local use
|
| 787 |
+
LOG_LOCAL2 = 18 # reserved for local use
|
| 788 |
+
LOG_LOCAL3 = 19 # reserved for local use
|
| 789 |
+
LOG_LOCAL4 = 20 # reserved for local use
|
| 790 |
+
LOG_LOCAL5 = 21 # reserved for local use
|
| 791 |
+
LOG_LOCAL6 = 22 # reserved for local use
|
| 792 |
+
LOG_LOCAL7 = 23 # reserved for local use
|
| 793 |
+
|
| 794 |
+
priority_names = {
|
| 795 |
+
"alert": LOG_ALERT,
|
| 796 |
+
"crit": LOG_CRIT,
|
| 797 |
+
"critical": LOG_CRIT,
|
| 798 |
+
"debug": LOG_DEBUG,
|
| 799 |
+
"emerg": LOG_EMERG,
|
| 800 |
+
"err": LOG_ERR,
|
| 801 |
+
"error": LOG_ERR, # DEPRECATED
|
| 802 |
+
"info": LOG_INFO,
|
| 803 |
+
"notice": LOG_NOTICE,
|
| 804 |
+
"panic": LOG_EMERG, # DEPRECATED
|
| 805 |
+
"warn": LOG_WARNING, # DEPRECATED
|
| 806 |
+
"warning": LOG_WARNING,
|
| 807 |
+
}
|
| 808 |
+
|
| 809 |
+
facility_names = {
|
| 810 |
+
"auth": LOG_AUTH,
|
| 811 |
+
"authpriv": LOG_AUTHPRIV,
|
| 812 |
+
"console": LOG_CONSOLE,
|
| 813 |
+
"cron": LOG_CRON,
|
| 814 |
+
"daemon": LOG_DAEMON,
|
| 815 |
+
"ftp": LOG_FTP,
|
| 816 |
+
"kern": LOG_KERN,
|
| 817 |
+
"lpr": LOG_LPR,
|
| 818 |
+
"mail": LOG_MAIL,
|
| 819 |
+
"news": LOG_NEWS,
|
| 820 |
+
"ntp": LOG_NTP,
|
| 821 |
+
"security": LOG_SECURITY,
|
| 822 |
+
"solaris-cron": LOG_SOLCRON,
|
| 823 |
+
"syslog": LOG_SYSLOG,
|
| 824 |
+
"user": LOG_USER,
|
| 825 |
+
"uucp": LOG_UUCP,
|
| 826 |
+
"local0": LOG_LOCAL0,
|
| 827 |
+
"local1": LOG_LOCAL1,
|
| 828 |
+
"local2": LOG_LOCAL2,
|
| 829 |
+
"local3": LOG_LOCAL3,
|
| 830 |
+
"local4": LOG_LOCAL4,
|
| 831 |
+
"local5": LOG_LOCAL5,
|
| 832 |
+
"local6": LOG_LOCAL6,
|
| 833 |
+
"local7": LOG_LOCAL7,
|
| 834 |
+
}
|
| 835 |
+
|
| 836 |
+
#The map below appears to be trivially lowercasing the key. However,
|
| 837 |
+
#there's more to it than meets the eye - in some locales, lowercasing
|
| 838 |
+
#gives unexpected results. See SF #1524081: in the Turkish locale,
|
| 839 |
+
#"INFO".lower() != "info"
|
| 840 |
+
priority_map = {
|
| 841 |
+
"DEBUG" : "debug",
|
| 842 |
+
"INFO" : "info",
|
| 843 |
+
"WARNING" : "warning",
|
| 844 |
+
"ERROR" : "error",
|
| 845 |
+
"CRITICAL" : "critical"
|
| 846 |
+
}
|
| 847 |
+
|
| 848 |
+
def __init__(self, address=('localhost', SYSLOG_UDP_PORT),
|
| 849 |
+
facility=LOG_USER, socktype=None):
|
| 850 |
+
"""
|
| 851 |
+
Initialize a handler.
|
| 852 |
+
|
| 853 |
+
If address is specified as a string, a UNIX socket is used. To log to a
|
| 854 |
+
local syslogd, "SysLogHandler(address="/dev/log")" can be used.
|
| 855 |
+
If facility is not specified, LOG_USER is used. If socktype is
|
| 856 |
+
specified as socket.SOCK_DGRAM or socket.SOCK_STREAM, that specific
|
| 857 |
+
socket type will be used. For Unix sockets, you can also specify a
|
| 858 |
+
socktype of None, in which case socket.SOCK_DGRAM will be used, falling
|
| 859 |
+
back to socket.SOCK_STREAM.
|
| 860 |
+
"""
|
| 861 |
+
logging.Handler.__init__(self)
|
| 862 |
+
|
| 863 |
+
self.address = address
|
| 864 |
+
self.facility = facility
|
| 865 |
+
self.socktype = socktype
|
| 866 |
+
|
| 867 |
+
if isinstance(address, str):
|
| 868 |
+
self.unixsocket = True
|
| 869 |
+
# Syslog server may be unavailable during handler initialisation.
|
| 870 |
+
# C's openlog() function also ignores connection errors.
|
| 871 |
+
# Moreover, we ignore these errors while logging, so it not worse
|
| 872 |
+
# to ignore it also here.
|
| 873 |
+
try:
|
| 874 |
+
self._connect_unixsocket(address)
|
| 875 |
+
except OSError:
|
| 876 |
+
pass
|
| 877 |
+
else:
|
| 878 |
+
self.unixsocket = False
|
| 879 |
+
if socktype is None:
|
| 880 |
+
socktype = socket.SOCK_DGRAM
|
| 881 |
+
host, port = address
|
| 882 |
+
ress = socket.getaddrinfo(host, port, 0, socktype)
|
| 883 |
+
if not ress:
|
| 884 |
+
raise OSError("getaddrinfo returns an empty list")
|
| 885 |
+
for res in ress:
|
| 886 |
+
af, socktype, proto, _, sa = res
|
| 887 |
+
err = sock = None
|
| 888 |
+
try:
|
| 889 |
+
sock = socket.socket(af, socktype, proto)
|
| 890 |
+
if socktype == socket.SOCK_STREAM:
|
| 891 |
+
sock.connect(sa)
|
| 892 |
+
break
|
| 893 |
+
except OSError as exc:
|
| 894 |
+
err = exc
|
| 895 |
+
if sock is not None:
|
| 896 |
+
sock.close()
|
| 897 |
+
if err is not None:
|
| 898 |
+
raise err
|
| 899 |
+
self.socket = sock
|
| 900 |
+
self.socktype = socktype
|
| 901 |
+
|
| 902 |
+
def _connect_unixsocket(self, address):
|
| 903 |
+
use_socktype = self.socktype
|
| 904 |
+
if use_socktype is None:
|
| 905 |
+
use_socktype = socket.SOCK_DGRAM
|
| 906 |
+
self.socket = socket.socket(socket.AF_UNIX, use_socktype)
|
| 907 |
+
try:
|
| 908 |
+
self.socket.connect(address)
|
| 909 |
+
# it worked, so set self.socktype to the used type
|
| 910 |
+
self.socktype = use_socktype
|
| 911 |
+
except OSError:
|
| 912 |
+
self.socket.close()
|
| 913 |
+
if self.socktype is not None:
|
| 914 |
+
# user didn't specify falling back, so fail
|
| 915 |
+
raise
|
| 916 |
+
use_socktype = socket.SOCK_STREAM
|
| 917 |
+
self.socket = socket.socket(socket.AF_UNIX, use_socktype)
|
| 918 |
+
try:
|
| 919 |
+
self.socket.connect(address)
|
| 920 |
+
# it worked, so set self.socktype to the used type
|
| 921 |
+
self.socktype = use_socktype
|
| 922 |
+
except OSError:
|
| 923 |
+
self.socket.close()
|
| 924 |
+
raise
|
| 925 |
+
|
| 926 |
+
def encodePriority(self, facility, priority):
|
| 927 |
+
"""
|
| 928 |
+
Encode the facility and priority. You can pass in strings or
|
| 929 |
+
integers - if strings are passed, the facility_names and
|
| 930 |
+
priority_names mapping dictionaries are used to convert them to
|
| 931 |
+
integers.
|
| 932 |
+
"""
|
| 933 |
+
if isinstance(facility, str):
|
| 934 |
+
facility = self.facility_names[facility]
|
| 935 |
+
if isinstance(priority, str):
|
| 936 |
+
priority = self.priority_names[priority]
|
| 937 |
+
return (facility << 3) | priority
|
| 938 |
+
|
| 939 |
+
def close(self):
|
| 940 |
+
"""
|
| 941 |
+
Closes the socket.
|
| 942 |
+
"""
|
| 943 |
+
self.acquire()
|
| 944 |
+
try:
|
| 945 |
+
self.socket.close()
|
| 946 |
+
logging.Handler.close(self)
|
| 947 |
+
finally:
|
| 948 |
+
self.release()
|
| 949 |
+
|
| 950 |
+
def mapPriority(self, levelName):
|
| 951 |
+
"""
|
| 952 |
+
Map a logging level name to a key in the priority_names map.
|
| 953 |
+
This is useful in two scenarios: when custom levels are being
|
| 954 |
+
used, and in the case where you can't do a straightforward
|
| 955 |
+
mapping by lowercasing the logging level name because of locale-
|
| 956 |
+
specific issues (see SF #1524081).
|
| 957 |
+
"""
|
| 958 |
+
return self.priority_map.get(levelName, "warning")
|
| 959 |
+
|
| 960 |
+
ident = '' # prepended to all messages
|
| 961 |
+
append_nul = True # some old syslog daemons expect a NUL terminator
|
| 962 |
+
|
| 963 |
+
def emit(self, record):
|
| 964 |
+
"""
|
| 965 |
+
Emit a record.
|
| 966 |
+
|
| 967 |
+
The record is formatted, and then sent to the syslog server. If
|
| 968 |
+
exception information is present, it is NOT sent to the server.
|
| 969 |
+
"""
|
| 970 |
+
try:
|
| 971 |
+
msg = self.format(record)
|
| 972 |
+
if self.ident:
|
| 973 |
+
msg = self.ident + msg
|
| 974 |
+
if self.append_nul:
|
| 975 |
+
msg += '\000'
|
| 976 |
+
|
| 977 |
+
# We need to convert record level to lowercase, maybe this will
|
| 978 |
+
# change in the future.
|
| 979 |
+
prio = '<%d>' % self.encodePriority(self.facility,
|
| 980 |
+
self.mapPriority(record.levelname))
|
| 981 |
+
prio = prio.encode('utf-8')
|
| 982 |
+
# Message is a string. Convert to bytes as required by RFC 5424
|
| 983 |
+
msg = msg.encode('utf-8')
|
| 984 |
+
msg = prio + msg
|
| 985 |
+
if self.unixsocket:
|
| 986 |
+
try:
|
| 987 |
+
self.socket.send(msg)
|
| 988 |
+
except OSError:
|
| 989 |
+
self.socket.close()
|
| 990 |
+
self._connect_unixsocket(self.address)
|
| 991 |
+
self.socket.send(msg)
|
| 992 |
+
elif self.socktype == socket.SOCK_DGRAM:
|
| 993 |
+
self.socket.sendto(msg, self.address)
|
| 994 |
+
else:
|
| 995 |
+
self.socket.sendall(msg)
|
| 996 |
+
except Exception:
|
| 997 |
+
self.handleError(record)
|
| 998 |
+
|
| 999 |
+
class SMTPHandler(logging.Handler):
|
| 1000 |
+
"""
|
| 1001 |
+
A handler class which sends an SMTP email for each logging event.
|
| 1002 |
+
"""
|
| 1003 |
+
def __init__(self, mailhost, fromaddr, toaddrs, subject,
|
| 1004 |
+
credentials=None, secure=None, timeout=5.0):
|
| 1005 |
+
"""
|
| 1006 |
+
Initialize the handler.
|
| 1007 |
+
|
| 1008 |
+
Initialize the instance with the from and to addresses and subject
|
| 1009 |
+
line of the email. To specify a non-standard SMTP port, use the
|
| 1010 |
+
(host, port) tuple format for the mailhost argument. To specify
|
| 1011 |
+
authentication credentials, supply a (username, password) tuple
|
| 1012 |
+
for the credentials argument. To specify the use of a secure
|
| 1013 |
+
protocol (TLS), pass in a tuple for the secure argument. This will
|
| 1014 |
+
only be used when authentication credentials are supplied. The tuple
|
| 1015 |
+
will be either an empty tuple, or a single-value tuple with the name
|
| 1016 |
+
of a keyfile, or a 2-value tuple with the names of the keyfile and
|
| 1017 |
+
certificate file. (This tuple is passed to the `starttls` method).
|
| 1018 |
+
A timeout in seconds can be specified for the SMTP connection (the
|
| 1019 |
+
default is one second).
|
| 1020 |
+
"""
|
| 1021 |
+
logging.Handler.__init__(self)
|
| 1022 |
+
if isinstance(mailhost, (list, tuple)):
|
| 1023 |
+
self.mailhost, self.mailport = mailhost
|
| 1024 |
+
else:
|
| 1025 |
+
self.mailhost, self.mailport = mailhost, None
|
| 1026 |
+
if isinstance(credentials, (list, tuple)):
|
| 1027 |
+
self.username, self.password = credentials
|
| 1028 |
+
else:
|
| 1029 |
+
self.username = None
|
| 1030 |
+
self.fromaddr = fromaddr
|
| 1031 |
+
if isinstance(toaddrs, str):
|
| 1032 |
+
toaddrs = [toaddrs]
|
| 1033 |
+
self.toaddrs = toaddrs
|
| 1034 |
+
self.subject = subject
|
| 1035 |
+
self.secure = secure
|
| 1036 |
+
self.timeout = timeout
|
| 1037 |
+
|
| 1038 |
+
def getSubject(self, record):
|
| 1039 |
+
"""
|
| 1040 |
+
Determine the subject for the email.
|
| 1041 |
+
|
| 1042 |
+
If you want to specify a subject line which is record-dependent,
|
| 1043 |
+
override this method.
|
| 1044 |
+
"""
|
| 1045 |
+
return self.subject
|
| 1046 |
+
|
| 1047 |
+
def emit(self, record):
|
| 1048 |
+
"""
|
| 1049 |
+
Emit a record.
|
| 1050 |
+
|
| 1051 |
+
Format the record and send it to the specified addressees.
|
| 1052 |
+
"""
|
| 1053 |
+
try:
|
| 1054 |
+
import smtplib
|
| 1055 |
+
from email.message import EmailMessage
|
| 1056 |
+
import email.utils
|
| 1057 |
+
|
| 1058 |
+
port = self.mailport
|
| 1059 |
+
if not port:
|
| 1060 |
+
port = smtplib.SMTP_PORT
|
| 1061 |
+
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
|
| 1062 |
+
msg = EmailMessage()
|
| 1063 |
+
msg['From'] = self.fromaddr
|
| 1064 |
+
msg['To'] = ','.join(self.toaddrs)
|
| 1065 |
+
msg['Subject'] = self.getSubject(record)
|
| 1066 |
+
msg['Date'] = email.utils.localtime()
|
| 1067 |
+
msg.set_content(self.format(record))
|
| 1068 |
+
if self.username:
|
| 1069 |
+
if self.secure is not None:
|
| 1070 |
+
smtp.ehlo()
|
| 1071 |
+
smtp.starttls(*self.secure)
|
| 1072 |
+
smtp.ehlo()
|
| 1073 |
+
smtp.login(self.username, self.password)
|
| 1074 |
+
smtp.send_message(msg)
|
| 1075 |
+
smtp.quit()
|
| 1076 |
+
except Exception:
|
| 1077 |
+
self.handleError(record)
|
| 1078 |
+
|
| 1079 |
+
class NTEventLogHandler(logging.Handler):
|
| 1080 |
+
"""
|
| 1081 |
+
A handler class which sends events to the NT Event Log. Adds a
|
| 1082 |
+
registry entry for the specified application name. If no dllname is
|
| 1083 |
+
provided, win32service.pyd (which contains some basic message
|
| 1084 |
+
placeholders) is used. Note that use of these placeholders will make
|
| 1085 |
+
your event logs big, as the entire message source is held in the log.
|
| 1086 |
+
If you want slimmer logs, you have to pass in the name of your own DLL
|
| 1087 |
+
which contains the message definitions you want to use in the event log.
|
| 1088 |
+
"""
|
| 1089 |
+
def __init__(self, appname, dllname=None, logtype="Application"):
|
| 1090 |
+
logging.Handler.__init__(self)
|
| 1091 |
+
try:
|
| 1092 |
+
import win32evtlogutil, win32evtlog
|
| 1093 |
+
self.appname = appname
|
| 1094 |
+
self._welu = win32evtlogutil
|
| 1095 |
+
if not dllname:
|
| 1096 |
+
dllname = os.path.split(self._welu.__file__)
|
| 1097 |
+
dllname = os.path.split(dllname[0])
|
| 1098 |
+
dllname = os.path.join(dllname[0], r'win32service.pyd')
|
| 1099 |
+
self.dllname = dllname
|
| 1100 |
+
self.logtype = logtype
|
| 1101 |
+
# Administrative privileges are required to add a source to the registry.
|
| 1102 |
+
# This may not be available for a user that just wants to add to an
|
| 1103 |
+
# existing source - handle this specific case.
|
| 1104 |
+
try:
|
| 1105 |
+
self._welu.AddSourceToRegistry(appname, dllname, logtype)
|
| 1106 |
+
except Exception as e:
|
| 1107 |
+
# This will probably be a pywintypes.error. Only raise if it's not
|
| 1108 |
+
# an "access denied" error, else let it pass
|
| 1109 |
+
if getattr(e, 'winerror', None) != 5: # not access denied
|
| 1110 |
+
raise
|
| 1111 |
+
self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
|
| 1112 |
+
self.typemap = {
|
| 1113 |
+
logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
|
| 1114 |
+
logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
|
| 1115 |
+
logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
|
| 1116 |
+
logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
|
| 1117 |
+
logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
|
| 1118 |
+
}
|
| 1119 |
+
except ImportError:
|
| 1120 |
+
print("The Python Win32 extensions for NT (service, event "\
|
| 1121 |
+
"logging) appear not to be available.")
|
| 1122 |
+
self._welu = None
|
| 1123 |
+
|
| 1124 |
+
def getMessageID(self, record):
|
| 1125 |
+
"""
|
| 1126 |
+
Return the message ID for the event record. If you are using your
|
| 1127 |
+
own messages, you could do this by having the msg passed to the
|
| 1128 |
+
logger being an ID rather than a formatting string. Then, in here,
|
| 1129 |
+
you could use a dictionary lookup to get the message ID. This
|
| 1130 |
+
version returns 1, which is the base message ID in win32service.pyd.
|
| 1131 |
+
"""
|
| 1132 |
+
return 1
|
| 1133 |
+
|
| 1134 |
+
def getEventCategory(self, record):
|
| 1135 |
+
"""
|
| 1136 |
+
Return the event category for the record.
|
| 1137 |
+
|
| 1138 |
+
Override this if you want to specify your own categories. This version
|
| 1139 |
+
returns 0.
|
| 1140 |
+
"""
|
| 1141 |
+
return 0
|
| 1142 |
+
|
| 1143 |
+
def getEventType(self, record):
|
| 1144 |
+
"""
|
| 1145 |
+
Return the event type for the record.
|
| 1146 |
+
|
| 1147 |
+
Override this if you want to specify your own types. This version does
|
| 1148 |
+
a mapping using the handler's typemap attribute, which is set up in
|
| 1149 |
+
__init__() to a dictionary which contains mappings for DEBUG, INFO,
|
| 1150 |
+
WARNING, ERROR and CRITICAL. If you are using your own levels you will
|
| 1151 |
+
either need to override this method or place a suitable dictionary in
|
| 1152 |
+
the handler's typemap attribute.
|
| 1153 |
+
"""
|
| 1154 |
+
return self.typemap.get(record.levelno, self.deftype)
|
| 1155 |
+
|
| 1156 |
+
def emit(self, record):
|
| 1157 |
+
"""
|
| 1158 |
+
Emit a record.
|
| 1159 |
+
|
| 1160 |
+
Determine the message ID, event category and event type. Then
|
| 1161 |
+
log the message in the NT event log.
|
| 1162 |
+
"""
|
| 1163 |
+
if self._welu:
|
| 1164 |
+
try:
|
| 1165 |
+
id = self.getMessageID(record)
|
| 1166 |
+
cat = self.getEventCategory(record)
|
| 1167 |
+
type = self.getEventType(record)
|
| 1168 |
+
msg = self.format(record)
|
| 1169 |
+
self._welu.ReportEvent(self.appname, id, cat, type, [msg])
|
| 1170 |
+
except Exception:
|
| 1171 |
+
self.handleError(record)
|
| 1172 |
+
|
| 1173 |
+
def close(self):
|
| 1174 |
+
"""
|
| 1175 |
+
Clean up this handler.
|
| 1176 |
+
|
| 1177 |
+
You can remove the application name from the registry as a
|
| 1178 |
+
source of event log entries. However, if you do this, you will
|
| 1179 |
+
not be able to see the events as you intended in the Event Log
|
| 1180 |
+
Viewer - it needs to be able to access the registry to get the
|
| 1181 |
+
DLL name.
|
| 1182 |
+
"""
|
| 1183 |
+
#self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
|
| 1184 |
+
logging.Handler.close(self)
|
| 1185 |
+
|
| 1186 |
+
class HTTPHandler(logging.Handler):
|
| 1187 |
+
"""
|
| 1188 |
+
A class which sends records to a web server, using either GET or
|
| 1189 |
+
POST semantics.
|
| 1190 |
+
"""
|
| 1191 |
+
def __init__(self, host, url, method="GET", secure=False, credentials=None,
|
| 1192 |
+
context=None):
|
| 1193 |
+
"""
|
| 1194 |
+
Initialize the instance with the host, the request URL, and the method
|
| 1195 |
+
("GET" or "POST")
|
| 1196 |
+
"""
|
| 1197 |
+
logging.Handler.__init__(self)
|
| 1198 |
+
method = method.upper()
|
| 1199 |
+
if method not in ["GET", "POST"]:
|
| 1200 |
+
raise ValueError("method must be GET or POST")
|
| 1201 |
+
if not secure and context is not None:
|
| 1202 |
+
raise ValueError("context parameter only makes sense "
|
| 1203 |
+
"with secure=True")
|
| 1204 |
+
self.host = host
|
| 1205 |
+
self.url = url
|
| 1206 |
+
self.method = method
|
| 1207 |
+
self.secure = secure
|
| 1208 |
+
self.credentials = credentials
|
| 1209 |
+
self.context = context
|
| 1210 |
+
|
| 1211 |
+
def mapLogRecord(self, record):
|
| 1212 |
+
"""
|
| 1213 |
+
Default implementation of mapping the log record into a dict
|
| 1214 |
+
that is sent as the CGI data. Overwrite in your class.
|
| 1215 |
+
Contributed by Franz Glasner.
|
| 1216 |
+
"""
|
| 1217 |
+
return record.__dict__
|
| 1218 |
+
|
| 1219 |
+
def getConnection(self, host, secure):
|
| 1220 |
+
"""
|
| 1221 |
+
get a HTTP[S]Connection.
|
| 1222 |
+
|
| 1223 |
+
Override when a custom connection is required, for example if
|
| 1224 |
+
there is a proxy.
|
| 1225 |
+
"""
|
| 1226 |
+
import http.client
|
| 1227 |
+
if secure:
|
| 1228 |
+
connection = http.client.HTTPSConnection(host, context=self.context)
|
| 1229 |
+
else:
|
| 1230 |
+
connection = http.client.HTTPConnection(host)
|
| 1231 |
+
return connection
|
| 1232 |
+
|
| 1233 |
+
def emit(self, record):
|
| 1234 |
+
"""
|
| 1235 |
+
Emit a record.
|
| 1236 |
+
|
| 1237 |
+
Send the record to the web server as a percent-encoded dictionary
|
| 1238 |
+
"""
|
| 1239 |
+
try:
|
| 1240 |
+
import urllib.parse
|
| 1241 |
+
host = self.host
|
| 1242 |
+
h = self.getConnection(host, self.secure)
|
| 1243 |
+
url = self.url
|
| 1244 |
+
data = urllib.parse.urlencode(self.mapLogRecord(record))
|
| 1245 |
+
if self.method == "GET":
|
| 1246 |
+
if (url.find('?') >= 0):
|
| 1247 |
+
sep = '&'
|
| 1248 |
+
else:
|
| 1249 |
+
sep = '?'
|
| 1250 |
+
url = url + "%c%s" % (sep, data)
|
| 1251 |
+
h.putrequest(self.method, url)
|
| 1252 |
+
# support multiple hosts on one IP address...
|
| 1253 |
+
# need to strip optional :port from host, if present
|
| 1254 |
+
i = host.find(":")
|
| 1255 |
+
if i >= 0:
|
| 1256 |
+
host = host[:i]
|
| 1257 |
+
# See issue #30904: putrequest call above already adds this header
|
| 1258 |
+
# on Python 3.x.
|
| 1259 |
+
# h.putheader("Host", host)
|
| 1260 |
+
if self.method == "POST":
|
| 1261 |
+
h.putheader("Content-type",
|
| 1262 |
+
"application/x-www-form-urlencoded")
|
| 1263 |
+
h.putheader("Content-length", str(len(data)))
|
| 1264 |
+
if self.credentials:
|
| 1265 |
+
import base64
|
| 1266 |
+
s = ('%s:%s' % self.credentials).encode('utf-8')
|
| 1267 |
+
s = 'Basic ' + base64.b64encode(s).strip().decode('ascii')
|
| 1268 |
+
h.putheader('Authorization', s)
|
| 1269 |
+
h.endheaders()
|
| 1270 |
+
if self.method == "POST":
|
| 1271 |
+
h.send(data.encode('utf-8'))
|
| 1272 |
+
h.getresponse() #can't do anything with the result
|
| 1273 |
+
except Exception:
|
| 1274 |
+
self.handleError(record)
|
| 1275 |
+
|
| 1276 |
+
class BufferingHandler(logging.Handler):
|
| 1277 |
+
"""
|
| 1278 |
+
A handler class which buffers logging records in memory. Whenever each
|
| 1279 |
+
record is added to the buffer, a check is made to see if the buffer should
|
| 1280 |
+
be flushed. If it should, then flush() is expected to do what's needed.
|
| 1281 |
+
"""
|
| 1282 |
+
def __init__(self, capacity):
|
| 1283 |
+
"""
|
| 1284 |
+
Initialize the handler with the buffer size.
|
| 1285 |
+
"""
|
| 1286 |
+
logging.Handler.__init__(self)
|
| 1287 |
+
self.capacity = capacity
|
| 1288 |
+
self.buffer = []
|
| 1289 |
+
|
| 1290 |
+
def shouldFlush(self, record):
|
| 1291 |
+
"""
|
| 1292 |
+
Should the handler flush its buffer?
|
| 1293 |
+
|
| 1294 |
+
Returns true if the buffer is up to capacity. This method can be
|
| 1295 |
+
overridden to implement custom flushing strategies.
|
| 1296 |
+
"""
|
| 1297 |
+
return (len(self.buffer) >= self.capacity)
|
| 1298 |
+
|
| 1299 |
+
def emit(self, record):
|
| 1300 |
+
"""
|
| 1301 |
+
Emit a record.
|
| 1302 |
+
|
| 1303 |
+
Append the record. If shouldFlush() tells us to, call flush() to process
|
| 1304 |
+
the buffer.
|
| 1305 |
+
"""
|
| 1306 |
+
self.buffer.append(record)
|
| 1307 |
+
if self.shouldFlush(record):
|
| 1308 |
+
self.flush()
|
| 1309 |
+
|
| 1310 |
+
def flush(self):
|
| 1311 |
+
"""
|
| 1312 |
+
Override to implement custom flushing behaviour.
|
| 1313 |
+
|
| 1314 |
+
This version just zaps the buffer to empty.
|
| 1315 |
+
"""
|
| 1316 |
+
self.acquire()
|
| 1317 |
+
try:
|
| 1318 |
+
self.buffer.clear()
|
| 1319 |
+
finally:
|
| 1320 |
+
self.release()
|
| 1321 |
+
|
| 1322 |
+
def close(self):
|
| 1323 |
+
"""
|
| 1324 |
+
Close the handler.
|
| 1325 |
+
|
| 1326 |
+
This version just flushes and chains to the parent class' close().
|
| 1327 |
+
"""
|
| 1328 |
+
try:
|
| 1329 |
+
self.flush()
|
| 1330 |
+
finally:
|
| 1331 |
+
logging.Handler.close(self)
|
| 1332 |
+
|
| 1333 |
+
class MemoryHandler(BufferingHandler):
|
| 1334 |
+
"""
|
| 1335 |
+
A handler class which buffers logging records in memory, periodically
|
| 1336 |
+
flushing them to a target handler. Flushing occurs whenever the buffer
|
| 1337 |
+
is full, or when an event of a certain severity or greater is seen.
|
| 1338 |
+
"""
|
| 1339 |
+
def __init__(self, capacity, flushLevel=logging.ERROR, target=None,
|
| 1340 |
+
flushOnClose=True):
|
| 1341 |
+
"""
|
| 1342 |
+
Initialize the handler with the buffer size, the level at which
|
| 1343 |
+
flushing should occur and an optional target.
|
| 1344 |
+
|
| 1345 |
+
Note that without a target being set either here or via setTarget(),
|
| 1346 |
+
a MemoryHandler is no use to anyone!
|
| 1347 |
+
|
| 1348 |
+
The ``flushOnClose`` argument is ``True`` for backward compatibility
|
| 1349 |
+
reasons - the old behaviour is that when the handler is closed, the
|
| 1350 |
+
buffer is flushed, even if the flush level hasn't been exceeded nor the
|
| 1351 |
+
capacity exceeded. To prevent this, set ``flushOnClose`` to ``False``.
|
| 1352 |
+
"""
|
| 1353 |
+
BufferingHandler.__init__(self, capacity)
|
| 1354 |
+
self.flushLevel = flushLevel
|
| 1355 |
+
self.target = target
|
| 1356 |
+
# See Issue #26559 for why this has been added
|
| 1357 |
+
self.flushOnClose = flushOnClose
|
| 1358 |
+
|
| 1359 |
+
def shouldFlush(self, record):
|
| 1360 |
+
"""
|
| 1361 |
+
Check for buffer full or a record at the flushLevel or higher.
|
| 1362 |
+
"""
|
| 1363 |
+
return (len(self.buffer) >= self.capacity) or \
|
| 1364 |
+
(record.levelno >= self.flushLevel)
|
| 1365 |
+
|
| 1366 |
+
def setTarget(self, target):
|
| 1367 |
+
"""
|
| 1368 |
+
Set the target handler for this handler.
|
| 1369 |
+
"""
|
| 1370 |
+
self.acquire()
|
| 1371 |
+
try:
|
| 1372 |
+
self.target = target
|
| 1373 |
+
finally:
|
| 1374 |
+
self.release()
|
| 1375 |
+
|
| 1376 |
+
def flush(self):
|
| 1377 |
+
"""
|
| 1378 |
+
For a MemoryHandler, flushing means just sending the buffered
|
| 1379 |
+
records to the target, if there is one. Override if you want
|
| 1380 |
+
different behaviour.
|
| 1381 |
+
|
| 1382 |
+
The record buffer is also cleared by this operation.
|
| 1383 |
+
"""
|
| 1384 |
+
self.acquire()
|
| 1385 |
+
try:
|
| 1386 |
+
if self.target:
|
| 1387 |
+
for record in self.buffer:
|
| 1388 |
+
self.target.handle(record)
|
| 1389 |
+
self.buffer.clear()
|
| 1390 |
+
finally:
|
| 1391 |
+
self.release()
|
| 1392 |
+
|
| 1393 |
+
def close(self):
|
| 1394 |
+
"""
|
| 1395 |
+
Flush, if appropriately configured, set the target to None and lose the
|
| 1396 |
+
buffer.
|
| 1397 |
+
"""
|
| 1398 |
+
try:
|
| 1399 |
+
if self.flushOnClose:
|
| 1400 |
+
self.flush()
|
| 1401 |
+
finally:
|
| 1402 |
+
self.acquire()
|
| 1403 |
+
try:
|
| 1404 |
+
self.target = None
|
| 1405 |
+
BufferingHandler.close(self)
|
| 1406 |
+
finally:
|
| 1407 |
+
self.release()
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
class QueueHandler(logging.Handler):
|
| 1411 |
+
"""
|
| 1412 |
+
This handler sends events to a queue. Typically, it would be used together
|
| 1413 |
+
with a multiprocessing Queue to centralise logging to file in one process
|
| 1414 |
+
(in a multi-process application), so as to avoid file write contention
|
| 1415 |
+
between processes.
|
| 1416 |
+
|
| 1417 |
+
This code is new in Python 3.2, but this class can be copy pasted into
|
| 1418 |
+
user code for use with earlier Python versions.
|
| 1419 |
+
"""
|
| 1420 |
+
|
| 1421 |
+
def __init__(self, queue):
|
| 1422 |
+
"""
|
| 1423 |
+
Initialise an instance, using the passed queue.
|
| 1424 |
+
"""
|
| 1425 |
+
logging.Handler.__init__(self)
|
| 1426 |
+
self.queue = queue
|
| 1427 |
+
|
| 1428 |
+
def enqueue(self, record):
|
| 1429 |
+
"""
|
| 1430 |
+
Enqueue a record.
|
| 1431 |
+
|
| 1432 |
+
The base implementation uses put_nowait. You may want to override
|
| 1433 |
+
this method if you want to use blocking, timeouts or custom queue
|
| 1434 |
+
implementations.
|
| 1435 |
+
"""
|
| 1436 |
+
self.queue.put_nowait(record)
|
| 1437 |
+
|
| 1438 |
+
def prepare(self, record):
|
| 1439 |
+
"""
|
| 1440 |
+
Prepares a record for queuing. The object returned by this method is
|
| 1441 |
+
enqueued.
|
| 1442 |
+
|
| 1443 |
+
The base implementation formats the record to merge the message
|
| 1444 |
+
and arguments, and removes unpickleable items from the record
|
| 1445 |
+
in-place.
|
| 1446 |
+
|
| 1447 |
+
You might want to override this method if you want to convert
|
| 1448 |
+
the record to a dict or JSON string, or send a modified copy
|
| 1449 |
+
of the record while leaving the original intact.
|
| 1450 |
+
"""
|
| 1451 |
+
# The format operation gets traceback text into record.exc_text
|
| 1452 |
+
# (if there's exception data), and also returns the formatted
|
| 1453 |
+
# message. We can then use this to replace the original
|
| 1454 |
+
# msg + args, as these might be unpickleable. We also zap the
|
| 1455 |
+
# exc_info, exc_text and stack_info attributes, as they are no longer
|
| 1456 |
+
# needed and, if not None, will typically not be pickleable.
|
| 1457 |
+
msg = self.format(record)
|
| 1458 |
+
# bpo-35726: make copy of record to avoid affecting other handlers in the chain.
|
| 1459 |
+
record = copy.copy(record)
|
| 1460 |
+
record.message = msg
|
| 1461 |
+
record.msg = msg
|
| 1462 |
+
record.args = None
|
| 1463 |
+
record.exc_info = None
|
| 1464 |
+
record.exc_text = None
|
| 1465 |
+
record.stack_info = None
|
| 1466 |
+
return record
|
| 1467 |
+
|
| 1468 |
+
def emit(self, record):
|
| 1469 |
+
"""
|
| 1470 |
+
Emit a record.
|
| 1471 |
+
|
| 1472 |
+
Writes the LogRecord to the queue, preparing it for pickling first.
|
| 1473 |
+
"""
|
| 1474 |
+
try:
|
| 1475 |
+
self.enqueue(self.prepare(record))
|
| 1476 |
+
except Exception:
|
| 1477 |
+
self.handleError(record)
|
| 1478 |
+
|
| 1479 |
+
|
| 1480 |
+
class QueueListener(object):
|
| 1481 |
+
"""
|
| 1482 |
+
This class implements an internal threaded listener which watches for
|
| 1483 |
+
LogRecords being added to a queue, removes them and passes them to a
|
| 1484 |
+
list of handlers for processing.
|
| 1485 |
+
"""
|
| 1486 |
+
_sentinel = None
|
| 1487 |
+
|
| 1488 |
+
def __init__(self, queue, *handlers, respect_handler_level=False):
|
| 1489 |
+
"""
|
| 1490 |
+
Initialise an instance with the specified queue and
|
| 1491 |
+
handlers.
|
| 1492 |
+
"""
|
| 1493 |
+
self.queue = queue
|
| 1494 |
+
self.handlers = handlers
|
| 1495 |
+
self._thread = None
|
| 1496 |
+
self.respect_handler_level = respect_handler_level
|
| 1497 |
+
|
| 1498 |
+
def dequeue(self, block):
|
| 1499 |
+
"""
|
| 1500 |
+
Dequeue a record and return it, optionally blocking.
|
| 1501 |
+
|
| 1502 |
+
The base implementation uses get. You may want to override this method
|
| 1503 |
+
if you want to use timeouts or work with custom queue implementations.
|
| 1504 |
+
"""
|
| 1505 |
+
return self.queue.get(block)
|
| 1506 |
+
|
| 1507 |
+
def start(self):
|
| 1508 |
+
"""
|
| 1509 |
+
Start the listener.
|
| 1510 |
+
|
| 1511 |
+
This starts up a background thread to monitor the queue for
|
| 1512 |
+
LogRecords to process.
|
| 1513 |
+
"""
|
| 1514 |
+
self._thread = t = threading.Thread(target=self._monitor)
|
| 1515 |
+
t.daemon = True
|
| 1516 |
+
t.start()
|
| 1517 |
+
|
| 1518 |
+
def prepare(self, record):
|
| 1519 |
+
"""
|
| 1520 |
+
Prepare a record for handling.
|
| 1521 |
+
|
| 1522 |
+
This method just returns the passed-in record. You may want to
|
| 1523 |
+
override this method if you need to do any custom marshalling or
|
| 1524 |
+
manipulation of the record before passing it to the handlers.
|
| 1525 |
+
"""
|
| 1526 |
+
return record
|
| 1527 |
+
|
| 1528 |
+
def handle(self, record):
|
| 1529 |
+
"""
|
| 1530 |
+
Handle a record.
|
| 1531 |
+
|
| 1532 |
+
This just loops through the handlers offering them the record
|
| 1533 |
+
to handle.
|
| 1534 |
+
"""
|
| 1535 |
+
record = self.prepare(record)
|
| 1536 |
+
for handler in self.handlers:
|
| 1537 |
+
if not self.respect_handler_level:
|
| 1538 |
+
process = True
|
| 1539 |
+
else:
|
| 1540 |
+
process = record.levelno >= handler.level
|
| 1541 |
+
if process:
|
| 1542 |
+
handler.handle(record)
|
| 1543 |
+
|
| 1544 |
+
def _monitor(self):
|
| 1545 |
+
"""
|
| 1546 |
+
Monitor the queue for records, and ask the handler
|
| 1547 |
+
to deal with them.
|
| 1548 |
+
|
| 1549 |
+
This method runs on a separate, internal thread.
|
| 1550 |
+
The thread will terminate if it sees a sentinel object in the queue.
|
| 1551 |
+
"""
|
| 1552 |
+
q = self.queue
|
| 1553 |
+
has_task_done = hasattr(q, 'task_done')
|
| 1554 |
+
while True:
|
| 1555 |
+
try:
|
| 1556 |
+
record = self.dequeue(True)
|
| 1557 |
+
if record is self._sentinel:
|
| 1558 |
+
if has_task_done:
|
| 1559 |
+
q.task_done()
|
| 1560 |
+
break
|
| 1561 |
+
self.handle(record)
|
| 1562 |
+
if has_task_done:
|
| 1563 |
+
q.task_done()
|
| 1564 |
+
except queue.Empty:
|
| 1565 |
+
break
|
| 1566 |
+
|
| 1567 |
+
def enqueue_sentinel(self):
|
| 1568 |
+
"""
|
| 1569 |
+
This is used to enqueue the sentinel record.
|
| 1570 |
+
|
| 1571 |
+
The base implementation uses put_nowait. You may want to override this
|
| 1572 |
+
method if you want to use timeouts or work with custom queue
|
| 1573 |
+
implementations.
|
| 1574 |
+
"""
|
| 1575 |
+
self.queue.put_nowait(self._sentinel)
|
| 1576 |
+
|
| 1577 |
+
def stop(self):
|
| 1578 |
+
"""
|
| 1579 |
+
Stop the listener.
|
| 1580 |
+
|
| 1581 |
+
This asks the thread to terminate, and then waits for it to do so.
|
| 1582 |
+
Note that if you don't call this before your application exits, there
|
| 1583 |
+
may be some records still left on the queue, which won't be processed.
|
| 1584 |
+
"""
|
| 1585 |
+
self.enqueue_sentinel()
|
| 1586 |
+
self._thread.join()
|
| 1587 |
+
self._thread = None
|
miniconda3/envs/ladir/lib/python3.10/multiprocessing/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Package analogous to 'threading.py' but using processes
|
| 3 |
+
#
|
| 4 |
+
# multiprocessing/__init__.py
|
| 5 |
+
#
|
| 6 |
+
# This package is intended to duplicate the functionality (and much of
|
| 7 |
+
# the API) of threading.py but uses processes instead of threads. A
|
| 8 |
+
# subpackage 'multiprocessing.dummy' has the same API but is a simple
|
| 9 |
+
# wrapper for 'threading'.
|
| 10 |
+
#
|
| 11 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 12 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 13 |
+
#
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
from . import context
|
| 17 |
+
|
| 18 |
+
#
|
| 19 |
+
# Copy stuff from default context
|
| 20 |
+
#
|
| 21 |
+
|
| 22 |
+
__all__ = [x for x in dir(context._default_context) if not x.startswith('_')]
|
| 23 |
+
globals().update((name, getattr(context._default_context, name)) for name in __all__)
|
| 24 |
+
|
| 25 |
+
#
|
| 26 |
+
# XXX These should not really be documented or public.
|
| 27 |
+
#
|
| 28 |
+
|
| 29 |
+
SUBDEBUG = 5
|
| 30 |
+
SUBWARNING = 25
|
| 31 |
+
|
| 32 |
+
#
|
| 33 |
+
# Alias for main module -- will be reset by bootstrapping child processes
|
| 34 |
+
#
|
| 35 |
+
|
| 36 |
+
if '__main__' in sys.modules:
|
| 37 |
+
sys.modules['__mp_main__'] = sys.modules['__main__']
|
miniconda3/envs/ladir/lib/python3.10/multiprocessing/connection.py
ADDED
|
@@ -0,0 +1,973 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# A higher level module for using sockets (or Windows named pipes)
|
| 3 |
+
#
|
| 4 |
+
# multiprocessing/connection.py
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 7 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 8 |
+
#
|
| 9 |
+
|
| 10 |
+
__all__ = [ 'Client', 'Listener', 'Pipe', 'wait' ]
|
| 11 |
+
|
| 12 |
+
import io
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import socket
|
| 16 |
+
import struct
|
| 17 |
+
import time
|
| 18 |
+
import tempfile
|
| 19 |
+
import itertools
|
| 20 |
+
|
| 21 |
+
import _multiprocessing
|
| 22 |
+
|
| 23 |
+
from . import util
|
| 24 |
+
|
| 25 |
+
from . import AuthenticationError, BufferTooShort
|
| 26 |
+
from .context import reduction
|
| 27 |
+
_ForkingPickler = reduction.ForkingPickler
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
import _winapi
|
| 31 |
+
from _winapi import WAIT_OBJECT_0, WAIT_ABANDONED_0, WAIT_TIMEOUT, INFINITE
|
| 32 |
+
except ImportError:
|
| 33 |
+
if sys.platform == 'win32':
|
| 34 |
+
raise
|
| 35 |
+
_winapi = None
|
| 36 |
+
|
| 37 |
+
#
|
| 38 |
+
#
|
| 39 |
+
#
|
| 40 |
+
|
| 41 |
+
BUFSIZE = 8192
|
| 42 |
+
# A very generous timeout when it comes to local connections...
|
| 43 |
+
CONNECTION_TIMEOUT = 20.
|
| 44 |
+
|
| 45 |
+
_mmap_counter = itertools.count()
|
| 46 |
+
|
| 47 |
+
default_family = 'AF_INET'
|
| 48 |
+
families = ['AF_INET']
|
| 49 |
+
|
| 50 |
+
if hasattr(socket, 'AF_UNIX'):
|
| 51 |
+
default_family = 'AF_UNIX'
|
| 52 |
+
families += ['AF_UNIX']
|
| 53 |
+
|
| 54 |
+
if sys.platform == 'win32':
|
| 55 |
+
default_family = 'AF_PIPE'
|
| 56 |
+
families += ['AF_PIPE']
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _init_timeout(timeout=CONNECTION_TIMEOUT):
|
| 60 |
+
return time.monotonic() + timeout
|
| 61 |
+
|
| 62 |
+
def _check_timeout(t):
|
| 63 |
+
return time.monotonic() > t
|
| 64 |
+
|
| 65 |
+
#
|
| 66 |
+
#
|
| 67 |
+
#
|
| 68 |
+
|
| 69 |
+
def arbitrary_address(family):
|
| 70 |
+
'''
|
| 71 |
+
Return an arbitrary free address for the given family
|
| 72 |
+
'''
|
| 73 |
+
if family == 'AF_INET':
|
| 74 |
+
return ('localhost', 0)
|
| 75 |
+
elif family == 'AF_UNIX':
|
| 76 |
+
return tempfile.mktemp(prefix='listener-', dir=util.get_temp_dir())
|
| 77 |
+
elif family == 'AF_PIPE':
|
| 78 |
+
return tempfile.mktemp(prefix=r'\\.\pipe\pyc-%d-%d-' %
|
| 79 |
+
(os.getpid(), next(_mmap_counter)), dir="")
|
| 80 |
+
else:
|
| 81 |
+
raise ValueError('unrecognized family')
|
| 82 |
+
|
| 83 |
+
def _validate_family(family):
|
| 84 |
+
'''
|
| 85 |
+
Checks if the family is valid for the current environment.
|
| 86 |
+
'''
|
| 87 |
+
if sys.platform != 'win32' and family == 'AF_PIPE':
|
| 88 |
+
raise ValueError('Family %s is not recognized.' % family)
|
| 89 |
+
|
| 90 |
+
if sys.platform == 'win32' and family == 'AF_UNIX':
|
| 91 |
+
# double check
|
| 92 |
+
if not hasattr(socket, family):
|
| 93 |
+
raise ValueError('Family %s is not recognized.' % family)
|
| 94 |
+
|
| 95 |
+
def address_type(address):
|
| 96 |
+
'''
|
| 97 |
+
Return the types of the address
|
| 98 |
+
|
| 99 |
+
This can be 'AF_INET', 'AF_UNIX', or 'AF_PIPE'
|
| 100 |
+
'''
|
| 101 |
+
if type(address) == tuple:
|
| 102 |
+
return 'AF_INET'
|
| 103 |
+
elif type(address) is str and address.startswith('\\\\'):
|
| 104 |
+
return 'AF_PIPE'
|
| 105 |
+
elif type(address) is str or util.is_abstract_socket_namespace(address):
|
| 106 |
+
return 'AF_UNIX'
|
| 107 |
+
else:
|
| 108 |
+
raise ValueError('address type of %r unrecognized' % address)
|
| 109 |
+
|
| 110 |
+
#
|
| 111 |
+
# Connection classes
|
| 112 |
+
#
|
| 113 |
+
|
| 114 |
+
class _ConnectionBase:
|
| 115 |
+
_handle = None
|
| 116 |
+
|
| 117 |
+
def __init__(self, handle, readable=True, writable=True):
|
| 118 |
+
handle = handle.__index__()
|
| 119 |
+
if handle < 0:
|
| 120 |
+
raise ValueError("invalid handle")
|
| 121 |
+
if not readable and not writable:
|
| 122 |
+
raise ValueError(
|
| 123 |
+
"at least one of `readable` and `writable` must be True")
|
| 124 |
+
self._handle = handle
|
| 125 |
+
self._readable = readable
|
| 126 |
+
self._writable = writable
|
| 127 |
+
|
| 128 |
+
# XXX should we use util.Finalize instead of a __del__?
|
| 129 |
+
|
| 130 |
+
def __del__(self):
|
| 131 |
+
if self._handle is not None:
|
| 132 |
+
self._close()
|
| 133 |
+
|
| 134 |
+
def _check_closed(self):
|
| 135 |
+
if self._handle is None:
|
| 136 |
+
raise OSError("handle is closed")
|
| 137 |
+
|
| 138 |
+
def _check_readable(self):
|
| 139 |
+
if not self._readable:
|
| 140 |
+
raise OSError("connection is write-only")
|
| 141 |
+
|
| 142 |
+
def _check_writable(self):
|
| 143 |
+
if not self._writable:
|
| 144 |
+
raise OSError("connection is read-only")
|
| 145 |
+
|
| 146 |
+
def _bad_message_length(self):
|
| 147 |
+
if self._writable:
|
| 148 |
+
self._readable = False
|
| 149 |
+
else:
|
| 150 |
+
self.close()
|
| 151 |
+
raise OSError("bad message length")
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def closed(self):
|
| 155 |
+
"""True if the connection is closed"""
|
| 156 |
+
return self._handle is None
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def readable(self):
|
| 160 |
+
"""True if the connection is readable"""
|
| 161 |
+
return self._readable
|
| 162 |
+
|
| 163 |
+
@property
|
| 164 |
+
def writable(self):
|
| 165 |
+
"""True if the connection is writable"""
|
| 166 |
+
return self._writable
|
| 167 |
+
|
| 168 |
+
def fileno(self):
|
| 169 |
+
"""File descriptor or handle of the connection"""
|
| 170 |
+
self._check_closed()
|
| 171 |
+
return self._handle
|
| 172 |
+
|
| 173 |
+
def close(self):
|
| 174 |
+
"""Close the connection"""
|
| 175 |
+
if self._handle is not None:
|
| 176 |
+
try:
|
| 177 |
+
self._close()
|
| 178 |
+
finally:
|
| 179 |
+
self._handle = None
|
| 180 |
+
|
| 181 |
+
def send_bytes(self, buf, offset=0, size=None):
|
| 182 |
+
"""Send the bytes data from a bytes-like object"""
|
| 183 |
+
self._check_closed()
|
| 184 |
+
self._check_writable()
|
| 185 |
+
m = memoryview(buf)
|
| 186 |
+
# HACK for byte-indexing of non-bytewise buffers (e.g. array.array)
|
| 187 |
+
if m.itemsize > 1:
|
| 188 |
+
m = memoryview(bytes(m))
|
| 189 |
+
n = len(m)
|
| 190 |
+
if offset < 0:
|
| 191 |
+
raise ValueError("offset is negative")
|
| 192 |
+
if n < offset:
|
| 193 |
+
raise ValueError("buffer length < offset")
|
| 194 |
+
if size is None:
|
| 195 |
+
size = n - offset
|
| 196 |
+
elif size < 0:
|
| 197 |
+
raise ValueError("size is negative")
|
| 198 |
+
elif offset + size > n:
|
| 199 |
+
raise ValueError("buffer length < offset + size")
|
| 200 |
+
self._send_bytes(m[offset:offset + size])
|
| 201 |
+
|
| 202 |
+
def send(self, obj):
|
| 203 |
+
"""Send a (picklable) object"""
|
| 204 |
+
self._check_closed()
|
| 205 |
+
self._check_writable()
|
| 206 |
+
self._send_bytes(_ForkingPickler.dumps(obj))
|
| 207 |
+
|
| 208 |
+
def recv_bytes(self, maxlength=None):
|
| 209 |
+
"""
|
| 210 |
+
Receive bytes data as a bytes object.
|
| 211 |
+
"""
|
| 212 |
+
self._check_closed()
|
| 213 |
+
self._check_readable()
|
| 214 |
+
if maxlength is not None and maxlength < 0:
|
| 215 |
+
raise ValueError("negative maxlength")
|
| 216 |
+
buf = self._recv_bytes(maxlength)
|
| 217 |
+
if buf is None:
|
| 218 |
+
self._bad_message_length()
|
| 219 |
+
return buf.getvalue()
|
| 220 |
+
|
| 221 |
+
def recv_bytes_into(self, buf, offset=0):
|
| 222 |
+
"""
|
| 223 |
+
Receive bytes data into a writeable bytes-like object.
|
| 224 |
+
Return the number of bytes read.
|
| 225 |
+
"""
|
| 226 |
+
self._check_closed()
|
| 227 |
+
self._check_readable()
|
| 228 |
+
with memoryview(buf) as m:
|
| 229 |
+
# Get bytesize of arbitrary buffer
|
| 230 |
+
itemsize = m.itemsize
|
| 231 |
+
bytesize = itemsize * len(m)
|
| 232 |
+
if offset < 0:
|
| 233 |
+
raise ValueError("negative offset")
|
| 234 |
+
elif offset > bytesize:
|
| 235 |
+
raise ValueError("offset too large")
|
| 236 |
+
result = self._recv_bytes()
|
| 237 |
+
size = result.tell()
|
| 238 |
+
if bytesize < offset + size:
|
| 239 |
+
raise BufferTooShort(result.getvalue())
|
| 240 |
+
# Message can fit in dest
|
| 241 |
+
result.seek(0)
|
| 242 |
+
result.readinto(m[offset // itemsize :
|
| 243 |
+
(offset + size) // itemsize])
|
| 244 |
+
return size
|
| 245 |
+
|
| 246 |
+
def recv(self):
|
| 247 |
+
"""Receive a (picklable) object"""
|
| 248 |
+
self._check_closed()
|
| 249 |
+
self._check_readable()
|
| 250 |
+
buf = self._recv_bytes()
|
| 251 |
+
return _ForkingPickler.loads(buf.getbuffer())
|
| 252 |
+
|
| 253 |
+
def poll(self, timeout=0.0):
|
| 254 |
+
"""Whether there is any input available to be read"""
|
| 255 |
+
self._check_closed()
|
| 256 |
+
self._check_readable()
|
| 257 |
+
return self._poll(timeout)
|
| 258 |
+
|
| 259 |
+
def __enter__(self):
|
| 260 |
+
return self
|
| 261 |
+
|
| 262 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
| 263 |
+
self.close()
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
if _winapi:
|
| 267 |
+
|
| 268 |
+
class PipeConnection(_ConnectionBase):
|
| 269 |
+
"""
|
| 270 |
+
Connection class based on a Windows named pipe.
|
| 271 |
+
Overlapped I/O is used, so the handles must have been created
|
| 272 |
+
with FILE_FLAG_OVERLAPPED.
|
| 273 |
+
"""
|
| 274 |
+
_got_empty_message = False
|
| 275 |
+
|
| 276 |
+
def _close(self, _CloseHandle=_winapi.CloseHandle):
|
| 277 |
+
_CloseHandle(self._handle)
|
| 278 |
+
|
| 279 |
+
def _send_bytes(self, buf):
|
| 280 |
+
ov, err = _winapi.WriteFile(self._handle, buf, overlapped=True)
|
| 281 |
+
try:
|
| 282 |
+
if err == _winapi.ERROR_IO_PENDING:
|
| 283 |
+
waitres = _winapi.WaitForMultipleObjects(
|
| 284 |
+
[ov.event], False, INFINITE)
|
| 285 |
+
assert waitres == WAIT_OBJECT_0
|
| 286 |
+
except:
|
| 287 |
+
ov.cancel()
|
| 288 |
+
raise
|
| 289 |
+
finally:
|
| 290 |
+
nwritten, err = ov.GetOverlappedResult(True)
|
| 291 |
+
assert err == 0
|
| 292 |
+
assert nwritten == len(buf)
|
| 293 |
+
|
| 294 |
+
def _recv_bytes(self, maxsize=None):
|
| 295 |
+
if self._got_empty_message:
|
| 296 |
+
self._got_empty_message = False
|
| 297 |
+
return io.BytesIO()
|
| 298 |
+
else:
|
| 299 |
+
bsize = 128 if maxsize is None else min(maxsize, 128)
|
| 300 |
+
try:
|
| 301 |
+
ov, err = _winapi.ReadFile(self._handle, bsize,
|
| 302 |
+
overlapped=True)
|
| 303 |
+
try:
|
| 304 |
+
if err == _winapi.ERROR_IO_PENDING:
|
| 305 |
+
waitres = _winapi.WaitForMultipleObjects(
|
| 306 |
+
[ov.event], False, INFINITE)
|
| 307 |
+
assert waitres == WAIT_OBJECT_0
|
| 308 |
+
except:
|
| 309 |
+
ov.cancel()
|
| 310 |
+
raise
|
| 311 |
+
finally:
|
| 312 |
+
nread, err = ov.GetOverlappedResult(True)
|
| 313 |
+
if err == 0:
|
| 314 |
+
f = io.BytesIO()
|
| 315 |
+
f.write(ov.getbuffer())
|
| 316 |
+
return f
|
| 317 |
+
elif err == _winapi.ERROR_MORE_DATA:
|
| 318 |
+
return self._get_more_data(ov, maxsize)
|
| 319 |
+
except OSError as e:
|
| 320 |
+
if e.winerror == _winapi.ERROR_BROKEN_PIPE:
|
| 321 |
+
raise EOFError
|
| 322 |
+
else:
|
| 323 |
+
raise
|
| 324 |
+
raise RuntimeError("shouldn't get here; expected KeyboardInterrupt")
|
| 325 |
+
|
| 326 |
+
def _poll(self, timeout):
|
| 327 |
+
if (self._got_empty_message or
|
| 328 |
+
_winapi.PeekNamedPipe(self._handle)[0] != 0):
|
| 329 |
+
return True
|
| 330 |
+
return bool(wait([self], timeout))
|
| 331 |
+
|
| 332 |
+
def _get_more_data(self, ov, maxsize):
|
| 333 |
+
buf = ov.getbuffer()
|
| 334 |
+
f = io.BytesIO()
|
| 335 |
+
f.write(buf)
|
| 336 |
+
left = _winapi.PeekNamedPipe(self._handle)[1]
|
| 337 |
+
assert left > 0
|
| 338 |
+
if maxsize is not None and len(buf) + left > maxsize:
|
| 339 |
+
self._bad_message_length()
|
| 340 |
+
ov, err = _winapi.ReadFile(self._handle, left, overlapped=True)
|
| 341 |
+
rbytes, err = ov.GetOverlappedResult(True)
|
| 342 |
+
assert err == 0
|
| 343 |
+
assert rbytes == left
|
| 344 |
+
f.write(ov.getbuffer())
|
| 345 |
+
return f
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
class Connection(_ConnectionBase):
|
| 349 |
+
"""
|
| 350 |
+
Connection class based on an arbitrary file descriptor (Unix only), or
|
| 351 |
+
a socket handle (Windows).
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
if _winapi:
|
| 355 |
+
def _close(self, _close=_multiprocessing.closesocket):
|
| 356 |
+
_close(self._handle)
|
| 357 |
+
_write = _multiprocessing.send
|
| 358 |
+
_read = _multiprocessing.recv
|
| 359 |
+
else:
|
| 360 |
+
def _close(self, _close=os.close):
|
| 361 |
+
_close(self._handle)
|
| 362 |
+
_write = os.write
|
| 363 |
+
_read = os.read
|
| 364 |
+
|
| 365 |
+
def _send(self, buf, write=_write):
|
| 366 |
+
remaining = len(buf)
|
| 367 |
+
while True:
|
| 368 |
+
n = write(self._handle, buf)
|
| 369 |
+
remaining -= n
|
| 370 |
+
if remaining == 0:
|
| 371 |
+
break
|
| 372 |
+
buf = buf[n:]
|
| 373 |
+
|
| 374 |
+
def _recv(self, size, read=_read):
|
| 375 |
+
buf = io.BytesIO()
|
| 376 |
+
handle = self._handle
|
| 377 |
+
remaining = size
|
| 378 |
+
while remaining > 0:
|
| 379 |
+
chunk = read(handle, remaining)
|
| 380 |
+
n = len(chunk)
|
| 381 |
+
if n == 0:
|
| 382 |
+
if remaining == size:
|
| 383 |
+
raise EOFError
|
| 384 |
+
else:
|
| 385 |
+
raise OSError("got end of file during message")
|
| 386 |
+
buf.write(chunk)
|
| 387 |
+
remaining -= n
|
| 388 |
+
return buf
|
| 389 |
+
|
| 390 |
+
def _send_bytes(self, buf):
|
| 391 |
+
n = len(buf)
|
| 392 |
+
if n > 0x7fffffff:
|
| 393 |
+
pre_header = struct.pack("!i", -1)
|
| 394 |
+
header = struct.pack("!Q", n)
|
| 395 |
+
self._send(pre_header)
|
| 396 |
+
self._send(header)
|
| 397 |
+
self._send(buf)
|
| 398 |
+
else:
|
| 399 |
+
# For wire compatibility with 3.7 and lower
|
| 400 |
+
header = struct.pack("!i", n)
|
| 401 |
+
if n > 16384:
|
| 402 |
+
# The payload is large so Nagle's algorithm won't be triggered
|
| 403 |
+
# and we'd better avoid the cost of concatenation.
|
| 404 |
+
self._send(header)
|
| 405 |
+
self._send(buf)
|
| 406 |
+
else:
|
| 407 |
+
# Issue #20540: concatenate before sending, to avoid delays due
|
| 408 |
+
# to Nagle's algorithm on a TCP socket.
|
| 409 |
+
# Also note we want to avoid sending a 0-length buffer separately,
|
| 410 |
+
# to avoid "broken pipe" errors if the other end closed the pipe.
|
| 411 |
+
self._send(header + buf)
|
| 412 |
+
|
| 413 |
+
def _recv_bytes(self, maxsize=None):
|
| 414 |
+
buf = self._recv(4)
|
| 415 |
+
size, = struct.unpack("!i", buf.getvalue())
|
| 416 |
+
if size == -1:
|
| 417 |
+
buf = self._recv(8)
|
| 418 |
+
size, = struct.unpack("!Q", buf.getvalue())
|
| 419 |
+
if maxsize is not None and size > maxsize:
|
| 420 |
+
return None
|
| 421 |
+
return self._recv(size)
|
| 422 |
+
|
| 423 |
+
def _poll(self, timeout):
|
| 424 |
+
r = wait([self], timeout)
|
| 425 |
+
return bool(r)
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
#
|
| 429 |
+
# Public functions
|
| 430 |
+
#
|
| 431 |
+
|
| 432 |
+
class Listener(object):
|
| 433 |
+
'''
|
| 434 |
+
Returns a listener object.
|
| 435 |
+
|
| 436 |
+
This is a wrapper for a bound socket which is 'listening' for
|
| 437 |
+
connections, or for a Windows named pipe.
|
| 438 |
+
'''
|
| 439 |
+
def __init__(self, address=None, family=None, backlog=1, authkey=None):
|
| 440 |
+
family = family or (address and address_type(address)) \
|
| 441 |
+
or default_family
|
| 442 |
+
address = address or arbitrary_address(family)
|
| 443 |
+
|
| 444 |
+
_validate_family(family)
|
| 445 |
+
if family == 'AF_PIPE':
|
| 446 |
+
self._listener = PipeListener(address, backlog)
|
| 447 |
+
else:
|
| 448 |
+
self._listener = SocketListener(address, family, backlog)
|
| 449 |
+
|
| 450 |
+
if authkey is not None and not isinstance(authkey, bytes):
|
| 451 |
+
raise TypeError('authkey should be a byte string')
|
| 452 |
+
|
| 453 |
+
self._authkey = authkey
|
| 454 |
+
|
| 455 |
+
def accept(self):
|
| 456 |
+
'''
|
| 457 |
+
Accept a connection on the bound socket or named pipe of `self`.
|
| 458 |
+
|
| 459 |
+
Returns a `Connection` object.
|
| 460 |
+
'''
|
| 461 |
+
if self._listener is None:
|
| 462 |
+
raise OSError('listener is closed')
|
| 463 |
+
c = self._listener.accept()
|
| 464 |
+
if self._authkey:
|
| 465 |
+
deliver_challenge(c, self._authkey)
|
| 466 |
+
answer_challenge(c, self._authkey)
|
| 467 |
+
return c
|
| 468 |
+
|
| 469 |
+
def close(self):
|
| 470 |
+
'''
|
| 471 |
+
Close the bound socket or named pipe of `self`.
|
| 472 |
+
'''
|
| 473 |
+
listener = self._listener
|
| 474 |
+
if listener is not None:
|
| 475 |
+
self._listener = None
|
| 476 |
+
listener.close()
|
| 477 |
+
|
| 478 |
+
@property
|
| 479 |
+
def address(self):
|
| 480 |
+
return self._listener._address
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def last_accepted(self):
|
| 484 |
+
return self._listener._last_accepted
|
| 485 |
+
|
| 486 |
+
def __enter__(self):
|
| 487 |
+
return self
|
| 488 |
+
|
| 489 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
| 490 |
+
self.close()
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def Client(address, family=None, authkey=None):
|
| 494 |
+
'''
|
| 495 |
+
Returns a connection to the address of a `Listener`
|
| 496 |
+
'''
|
| 497 |
+
family = family or address_type(address)
|
| 498 |
+
_validate_family(family)
|
| 499 |
+
if family == 'AF_PIPE':
|
| 500 |
+
c = PipeClient(address)
|
| 501 |
+
else:
|
| 502 |
+
c = SocketClient(address)
|
| 503 |
+
|
| 504 |
+
if authkey is not None and not isinstance(authkey, bytes):
|
| 505 |
+
raise TypeError('authkey should be a byte string')
|
| 506 |
+
|
| 507 |
+
if authkey is not None:
|
| 508 |
+
answer_challenge(c, authkey)
|
| 509 |
+
deliver_challenge(c, authkey)
|
| 510 |
+
|
| 511 |
+
return c
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
if sys.platform != 'win32':
|
| 515 |
+
|
| 516 |
+
def Pipe(duplex=True):
|
| 517 |
+
'''
|
| 518 |
+
Returns pair of connection objects at either end of a pipe
|
| 519 |
+
'''
|
| 520 |
+
if duplex:
|
| 521 |
+
s1, s2 = socket.socketpair()
|
| 522 |
+
s1.setblocking(True)
|
| 523 |
+
s2.setblocking(True)
|
| 524 |
+
c1 = Connection(s1.detach())
|
| 525 |
+
c2 = Connection(s2.detach())
|
| 526 |
+
else:
|
| 527 |
+
fd1, fd2 = os.pipe()
|
| 528 |
+
c1 = Connection(fd1, writable=False)
|
| 529 |
+
c2 = Connection(fd2, readable=False)
|
| 530 |
+
|
| 531 |
+
return c1, c2
|
| 532 |
+
|
| 533 |
+
else:
|
| 534 |
+
|
| 535 |
+
def Pipe(duplex=True):
|
| 536 |
+
'''
|
| 537 |
+
Returns pair of connection objects at either end of a pipe
|
| 538 |
+
'''
|
| 539 |
+
address = arbitrary_address('AF_PIPE')
|
| 540 |
+
if duplex:
|
| 541 |
+
openmode = _winapi.PIPE_ACCESS_DUPLEX
|
| 542 |
+
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
|
| 543 |
+
obsize, ibsize = BUFSIZE, BUFSIZE
|
| 544 |
+
else:
|
| 545 |
+
openmode = _winapi.PIPE_ACCESS_INBOUND
|
| 546 |
+
access = _winapi.GENERIC_WRITE
|
| 547 |
+
obsize, ibsize = 0, BUFSIZE
|
| 548 |
+
|
| 549 |
+
h1 = _winapi.CreateNamedPipe(
|
| 550 |
+
address, openmode | _winapi.FILE_FLAG_OVERLAPPED |
|
| 551 |
+
_winapi.FILE_FLAG_FIRST_PIPE_INSTANCE,
|
| 552 |
+
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
|
| 553 |
+
_winapi.PIPE_WAIT,
|
| 554 |
+
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER,
|
| 555 |
+
# default security descriptor: the handle cannot be inherited
|
| 556 |
+
_winapi.NULL
|
| 557 |
+
)
|
| 558 |
+
h2 = _winapi.CreateFile(
|
| 559 |
+
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
|
| 560 |
+
_winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
|
| 561 |
+
)
|
| 562 |
+
_winapi.SetNamedPipeHandleState(
|
| 563 |
+
h2, _winapi.PIPE_READMODE_MESSAGE, None, None
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
overlapped = _winapi.ConnectNamedPipe(h1, overlapped=True)
|
| 567 |
+
_, err = overlapped.GetOverlappedResult(True)
|
| 568 |
+
assert err == 0
|
| 569 |
+
|
| 570 |
+
c1 = PipeConnection(h1, writable=duplex)
|
| 571 |
+
c2 = PipeConnection(h2, readable=duplex)
|
| 572 |
+
|
| 573 |
+
return c1, c2
|
| 574 |
+
|
| 575 |
+
#
|
| 576 |
+
# Definitions for connections based on sockets
|
| 577 |
+
#
|
| 578 |
+
|
| 579 |
+
class SocketListener(object):
|
| 580 |
+
'''
|
| 581 |
+
Representation of a socket which is bound to an address and listening
|
| 582 |
+
'''
|
| 583 |
+
def __init__(self, address, family, backlog=1):
|
| 584 |
+
self._socket = socket.socket(getattr(socket, family))
|
| 585 |
+
try:
|
| 586 |
+
# SO_REUSEADDR has different semantics on Windows (issue #2550).
|
| 587 |
+
if os.name == 'posix':
|
| 588 |
+
self._socket.setsockopt(socket.SOL_SOCKET,
|
| 589 |
+
socket.SO_REUSEADDR, 1)
|
| 590 |
+
self._socket.setblocking(True)
|
| 591 |
+
self._socket.bind(address)
|
| 592 |
+
self._socket.listen(backlog)
|
| 593 |
+
self._address = self._socket.getsockname()
|
| 594 |
+
except OSError:
|
| 595 |
+
self._socket.close()
|
| 596 |
+
raise
|
| 597 |
+
self._family = family
|
| 598 |
+
self._last_accepted = None
|
| 599 |
+
|
| 600 |
+
if family == 'AF_UNIX' and not util.is_abstract_socket_namespace(address):
|
| 601 |
+
# Linux abstract socket namespaces do not need to be explicitly unlinked
|
| 602 |
+
self._unlink = util.Finalize(
|
| 603 |
+
self, os.unlink, args=(address,), exitpriority=0
|
| 604 |
+
)
|
| 605 |
+
else:
|
| 606 |
+
self._unlink = None
|
| 607 |
+
|
| 608 |
+
def accept(self):
|
| 609 |
+
s, self._last_accepted = self._socket.accept()
|
| 610 |
+
s.setblocking(True)
|
| 611 |
+
return Connection(s.detach())
|
| 612 |
+
|
| 613 |
+
def close(self):
|
| 614 |
+
try:
|
| 615 |
+
self._socket.close()
|
| 616 |
+
finally:
|
| 617 |
+
unlink = self._unlink
|
| 618 |
+
if unlink is not None:
|
| 619 |
+
self._unlink = None
|
| 620 |
+
unlink()
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def SocketClient(address):
|
| 624 |
+
'''
|
| 625 |
+
Return a connection object connected to the socket given by `address`
|
| 626 |
+
'''
|
| 627 |
+
family = address_type(address)
|
| 628 |
+
with socket.socket( getattr(socket, family) ) as s:
|
| 629 |
+
s.setblocking(True)
|
| 630 |
+
s.connect(address)
|
| 631 |
+
return Connection(s.detach())
|
| 632 |
+
|
| 633 |
+
#
|
| 634 |
+
# Definitions for connections based on named pipes
|
| 635 |
+
#
|
| 636 |
+
|
| 637 |
+
if sys.platform == 'win32':
|
| 638 |
+
|
| 639 |
+
class PipeListener(object):
|
| 640 |
+
'''
|
| 641 |
+
Representation of a named pipe
|
| 642 |
+
'''
|
| 643 |
+
def __init__(self, address, backlog=None):
|
| 644 |
+
self._address = address
|
| 645 |
+
self._handle_queue = [self._new_handle(first=True)]
|
| 646 |
+
|
| 647 |
+
self._last_accepted = None
|
| 648 |
+
util.sub_debug('listener created with address=%r', self._address)
|
| 649 |
+
self.close = util.Finalize(
|
| 650 |
+
self, PipeListener._finalize_pipe_listener,
|
| 651 |
+
args=(self._handle_queue, self._address), exitpriority=0
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
def _new_handle(self, first=False):
|
| 655 |
+
flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
|
| 656 |
+
if first:
|
| 657 |
+
flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 658 |
+
return _winapi.CreateNamedPipe(
|
| 659 |
+
self._address, flags,
|
| 660 |
+
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
|
| 661 |
+
_winapi.PIPE_WAIT,
|
| 662 |
+
_winapi.PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE,
|
| 663 |
+
_winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
def accept(self):
|
| 667 |
+
self._handle_queue.append(self._new_handle())
|
| 668 |
+
handle = self._handle_queue.pop(0)
|
| 669 |
+
try:
|
| 670 |
+
ov = _winapi.ConnectNamedPipe(handle, overlapped=True)
|
| 671 |
+
except OSError as e:
|
| 672 |
+
if e.winerror != _winapi.ERROR_NO_DATA:
|
| 673 |
+
raise
|
| 674 |
+
# ERROR_NO_DATA can occur if a client has already connected,
|
| 675 |
+
# written data and then disconnected -- see Issue 14725.
|
| 676 |
+
else:
|
| 677 |
+
try:
|
| 678 |
+
res = _winapi.WaitForMultipleObjects(
|
| 679 |
+
[ov.event], False, INFINITE)
|
| 680 |
+
except:
|
| 681 |
+
ov.cancel()
|
| 682 |
+
_winapi.CloseHandle(handle)
|
| 683 |
+
raise
|
| 684 |
+
finally:
|
| 685 |
+
_, err = ov.GetOverlappedResult(True)
|
| 686 |
+
assert err == 0
|
| 687 |
+
return PipeConnection(handle)
|
| 688 |
+
|
| 689 |
+
@staticmethod
|
| 690 |
+
def _finalize_pipe_listener(queue, address):
|
| 691 |
+
util.sub_debug('closing listener with address=%r', address)
|
| 692 |
+
for handle in queue:
|
| 693 |
+
_winapi.CloseHandle(handle)
|
| 694 |
+
|
| 695 |
+
def PipeClient(address):
|
| 696 |
+
'''
|
| 697 |
+
Return a connection object connected to the pipe given by `address`
|
| 698 |
+
'''
|
| 699 |
+
t = _init_timeout()
|
| 700 |
+
while 1:
|
| 701 |
+
try:
|
| 702 |
+
_winapi.WaitNamedPipe(address, 1000)
|
| 703 |
+
h = _winapi.CreateFile(
|
| 704 |
+
address, _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,
|
| 705 |
+
0, _winapi.NULL, _winapi.OPEN_EXISTING,
|
| 706 |
+
_winapi.FILE_FLAG_OVERLAPPED, _winapi.NULL
|
| 707 |
+
)
|
| 708 |
+
except OSError as e:
|
| 709 |
+
if e.winerror not in (_winapi.ERROR_SEM_TIMEOUT,
|
| 710 |
+
_winapi.ERROR_PIPE_BUSY) or _check_timeout(t):
|
| 711 |
+
raise
|
| 712 |
+
else:
|
| 713 |
+
break
|
| 714 |
+
else:
|
| 715 |
+
raise
|
| 716 |
+
|
| 717 |
+
_winapi.SetNamedPipeHandleState(
|
| 718 |
+
h, _winapi.PIPE_READMODE_MESSAGE, None, None
|
| 719 |
+
)
|
| 720 |
+
return PipeConnection(h)
|
| 721 |
+
|
| 722 |
+
#
|
| 723 |
+
# Authentication stuff
|
| 724 |
+
#
|
| 725 |
+
|
| 726 |
+
MESSAGE_LENGTH = 20
|
| 727 |
+
|
| 728 |
+
CHALLENGE = b'#CHALLENGE#'
|
| 729 |
+
WELCOME = b'#WELCOME#'
|
| 730 |
+
FAILURE = b'#FAILURE#'
|
| 731 |
+
|
| 732 |
+
def deliver_challenge(connection, authkey):
|
| 733 |
+
import hmac
|
| 734 |
+
if not isinstance(authkey, bytes):
|
| 735 |
+
raise ValueError(
|
| 736 |
+
"Authkey must be bytes, not {0!s}".format(type(authkey)))
|
| 737 |
+
message = os.urandom(MESSAGE_LENGTH)
|
| 738 |
+
connection.send_bytes(CHALLENGE + message)
|
| 739 |
+
digest = hmac.new(authkey, message, 'md5').digest()
|
| 740 |
+
response = connection.recv_bytes(256) # reject large message
|
| 741 |
+
if response == digest:
|
| 742 |
+
connection.send_bytes(WELCOME)
|
| 743 |
+
else:
|
| 744 |
+
connection.send_bytes(FAILURE)
|
| 745 |
+
raise AuthenticationError('digest received was wrong')
|
| 746 |
+
|
| 747 |
+
def answer_challenge(connection, authkey):
|
| 748 |
+
import hmac
|
| 749 |
+
if not isinstance(authkey, bytes):
|
| 750 |
+
raise ValueError(
|
| 751 |
+
"Authkey must be bytes, not {0!s}".format(type(authkey)))
|
| 752 |
+
message = connection.recv_bytes(256) # reject large message
|
| 753 |
+
assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
|
| 754 |
+
message = message[len(CHALLENGE):]
|
| 755 |
+
digest = hmac.new(authkey, message, 'md5').digest()
|
| 756 |
+
connection.send_bytes(digest)
|
| 757 |
+
response = connection.recv_bytes(256) # reject large message
|
| 758 |
+
if response != WELCOME:
|
| 759 |
+
raise AuthenticationError('digest sent was rejected')
|
| 760 |
+
|
| 761 |
+
#
|
| 762 |
+
# Support for using xmlrpclib for serialization
|
| 763 |
+
#
|
| 764 |
+
|
| 765 |
+
class ConnectionWrapper(object):
|
| 766 |
+
def __init__(self, conn, dumps, loads):
|
| 767 |
+
self._conn = conn
|
| 768 |
+
self._dumps = dumps
|
| 769 |
+
self._loads = loads
|
| 770 |
+
for attr in ('fileno', 'close', 'poll', 'recv_bytes', 'send_bytes'):
|
| 771 |
+
obj = getattr(conn, attr)
|
| 772 |
+
setattr(self, attr, obj)
|
| 773 |
+
def send(self, obj):
|
| 774 |
+
s = self._dumps(obj)
|
| 775 |
+
self._conn.send_bytes(s)
|
| 776 |
+
def recv(self):
|
| 777 |
+
s = self._conn.recv_bytes()
|
| 778 |
+
return self._loads(s)
|
| 779 |
+
|
| 780 |
+
def _xml_dumps(obj):
|
| 781 |
+
return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8')
|
| 782 |
+
|
| 783 |
+
def _xml_loads(s):
|
| 784 |
+
(obj,), method = xmlrpclib.loads(s.decode('utf-8'))
|
| 785 |
+
return obj
|
| 786 |
+
|
| 787 |
+
class XmlListener(Listener):
|
| 788 |
+
def accept(self):
|
| 789 |
+
global xmlrpclib
|
| 790 |
+
import xmlrpc.client as xmlrpclib
|
| 791 |
+
obj = Listener.accept(self)
|
| 792 |
+
return ConnectionWrapper(obj, _xml_dumps, _xml_loads)
|
| 793 |
+
|
| 794 |
+
def XmlClient(*args, **kwds):
|
| 795 |
+
global xmlrpclib
|
| 796 |
+
import xmlrpc.client as xmlrpclib
|
| 797 |
+
return ConnectionWrapper(Client(*args, **kwds), _xml_dumps, _xml_loads)
|
| 798 |
+
|
| 799 |
+
#
|
| 800 |
+
# Wait
|
| 801 |
+
#
|
| 802 |
+
|
| 803 |
+
if sys.platform == 'win32':
|
| 804 |
+
|
| 805 |
+
def _exhaustive_wait(handles, timeout):
|
| 806 |
+
# Return ALL handles which are currently signalled. (Only
|
| 807 |
+
# returning the first signalled might create starvation issues.)
|
| 808 |
+
L = list(handles)
|
| 809 |
+
ready = []
|
| 810 |
+
while L:
|
| 811 |
+
res = _winapi.WaitForMultipleObjects(L, False, timeout)
|
| 812 |
+
if res == WAIT_TIMEOUT:
|
| 813 |
+
break
|
| 814 |
+
elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L):
|
| 815 |
+
res -= WAIT_OBJECT_0
|
| 816 |
+
elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L):
|
| 817 |
+
res -= WAIT_ABANDONED_0
|
| 818 |
+
else:
|
| 819 |
+
raise RuntimeError('Should not get here')
|
| 820 |
+
ready.append(L[res])
|
| 821 |
+
L = L[res+1:]
|
| 822 |
+
timeout = 0
|
| 823 |
+
return ready
|
| 824 |
+
|
| 825 |
+
_ready_errors = {_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED}
|
| 826 |
+
|
| 827 |
+
def wait(object_list, timeout=None):
|
| 828 |
+
'''
|
| 829 |
+
Wait till an object in object_list is ready/readable.
|
| 830 |
+
|
| 831 |
+
Returns list of those objects in object_list which are ready/readable.
|
| 832 |
+
'''
|
| 833 |
+
if timeout is None:
|
| 834 |
+
timeout = INFINITE
|
| 835 |
+
elif timeout < 0:
|
| 836 |
+
timeout = 0
|
| 837 |
+
else:
|
| 838 |
+
timeout = int(timeout * 1000 + 0.5)
|
| 839 |
+
|
| 840 |
+
object_list = list(object_list)
|
| 841 |
+
waithandle_to_obj = {}
|
| 842 |
+
ov_list = []
|
| 843 |
+
ready_objects = set()
|
| 844 |
+
ready_handles = set()
|
| 845 |
+
|
| 846 |
+
try:
|
| 847 |
+
for o in object_list:
|
| 848 |
+
try:
|
| 849 |
+
fileno = getattr(o, 'fileno')
|
| 850 |
+
except AttributeError:
|
| 851 |
+
waithandle_to_obj[o.__index__()] = o
|
| 852 |
+
else:
|
| 853 |
+
# start an overlapped read of length zero
|
| 854 |
+
try:
|
| 855 |
+
ov, err = _winapi.ReadFile(fileno(), 0, True)
|
| 856 |
+
except OSError as e:
|
| 857 |
+
ov, err = None, e.winerror
|
| 858 |
+
if err not in _ready_errors:
|
| 859 |
+
raise
|
| 860 |
+
if err == _winapi.ERROR_IO_PENDING:
|
| 861 |
+
ov_list.append(ov)
|
| 862 |
+
waithandle_to_obj[ov.event] = o
|
| 863 |
+
else:
|
| 864 |
+
# If o.fileno() is an overlapped pipe handle and
|
| 865 |
+
# err == 0 then there is a zero length message
|
| 866 |
+
# in the pipe, but it HAS NOT been consumed...
|
| 867 |
+
if ov and sys.getwindowsversion()[:2] >= (6, 2):
|
| 868 |
+
# ... except on Windows 8 and later, where
|
| 869 |
+
# the message HAS been consumed.
|
| 870 |
+
try:
|
| 871 |
+
_, err = ov.GetOverlappedResult(False)
|
| 872 |
+
except OSError as e:
|
| 873 |
+
err = e.winerror
|
| 874 |
+
if not err and hasattr(o, '_got_empty_message'):
|
| 875 |
+
o._got_empty_message = True
|
| 876 |
+
ready_objects.add(o)
|
| 877 |
+
timeout = 0
|
| 878 |
+
|
| 879 |
+
ready_handles = _exhaustive_wait(waithandle_to_obj.keys(), timeout)
|
| 880 |
+
finally:
|
| 881 |
+
# request that overlapped reads stop
|
| 882 |
+
for ov in ov_list:
|
| 883 |
+
ov.cancel()
|
| 884 |
+
|
| 885 |
+
# wait for all overlapped reads to stop
|
| 886 |
+
for ov in ov_list:
|
| 887 |
+
try:
|
| 888 |
+
_, err = ov.GetOverlappedResult(True)
|
| 889 |
+
except OSError as e:
|
| 890 |
+
err = e.winerror
|
| 891 |
+
if err not in _ready_errors:
|
| 892 |
+
raise
|
| 893 |
+
if err != _winapi.ERROR_OPERATION_ABORTED:
|
| 894 |
+
o = waithandle_to_obj[ov.event]
|
| 895 |
+
ready_objects.add(o)
|
| 896 |
+
if err == 0:
|
| 897 |
+
# If o.fileno() is an overlapped pipe handle then
|
| 898 |
+
# a zero length message HAS been consumed.
|
| 899 |
+
if hasattr(o, '_got_empty_message'):
|
| 900 |
+
o._got_empty_message = True
|
| 901 |
+
|
| 902 |
+
ready_objects.update(waithandle_to_obj[h] for h in ready_handles)
|
| 903 |
+
return [o for o in object_list if o in ready_objects]
|
| 904 |
+
|
| 905 |
+
else:
|
| 906 |
+
|
| 907 |
+
import selectors
|
| 908 |
+
|
| 909 |
+
# poll/select have the advantage of not requiring any extra file
|
| 910 |
+
# descriptor, contrarily to epoll/kqueue (also, they require a single
|
| 911 |
+
# syscall).
|
| 912 |
+
if hasattr(selectors, 'PollSelector'):
|
| 913 |
+
_WaitSelector = selectors.PollSelector
|
| 914 |
+
else:
|
| 915 |
+
_WaitSelector = selectors.SelectSelector
|
| 916 |
+
|
| 917 |
+
def wait(object_list, timeout=None):
|
| 918 |
+
'''
|
| 919 |
+
Wait till an object in object_list is ready/readable.
|
| 920 |
+
|
| 921 |
+
Returns list of those objects in object_list which are ready/readable.
|
| 922 |
+
'''
|
| 923 |
+
with _WaitSelector() as selector:
|
| 924 |
+
for obj in object_list:
|
| 925 |
+
selector.register(obj, selectors.EVENT_READ)
|
| 926 |
+
|
| 927 |
+
if timeout is not None:
|
| 928 |
+
deadline = time.monotonic() + timeout
|
| 929 |
+
|
| 930 |
+
while True:
|
| 931 |
+
ready = selector.select(timeout)
|
| 932 |
+
if ready:
|
| 933 |
+
return [key.fileobj for (key, events) in ready]
|
| 934 |
+
else:
|
| 935 |
+
if timeout is not None:
|
| 936 |
+
timeout = deadline - time.monotonic()
|
| 937 |
+
if timeout < 0:
|
| 938 |
+
return ready
|
| 939 |
+
|
| 940 |
+
#
|
| 941 |
+
# Make connection and socket objects sharable if possible
|
| 942 |
+
#
|
| 943 |
+
|
| 944 |
+
if sys.platform == 'win32':
|
| 945 |
+
def reduce_connection(conn):
|
| 946 |
+
handle = conn.fileno()
|
| 947 |
+
with socket.fromfd(handle, socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 948 |
+
from . import resource_sharer
|
| 949 |
+
ds = resource_sharer.DupSocket(s)
|
| 950 |
+
return rebuild_connection, (ds, conn.readable, conn.writable)
|
| 951 |
+
def rebuild_connection(ds, readable, writable):
|
| 952 |
+
sock = ds.detach()
|
| 953 |
+
return Connection(sock.detach(), readable, writable)
|
| 954 |
+
reduction.register(Connection, reduce_connection)
|
| 955 |
+
|
| 956 |
+
def reduce_pipe_connection(conn):
|
| 957 |
+
access = ((_winapi.FILE_GENERIC_READ if conn.readable else 0) |
|
| 958 |
+
(_winapi.FILE_GENERIC_WRITE if conn.writable else 0))
|
| 959 |
+
dh = reduction.DupHandle(conn.fileno(), access)
|
| 960 |
+
return rebuild_pipe_connection, (dh, conn.readable, conn.writable)
|
| 961 |
+
def rebuild_pipe_connection(dh, readable, writable):
|
| 962 |
+
handle = dh.detach()
|
| 963 |
+
return PipeConnection(handle, readable, writable)
|
| 964 |
+
reduction.register(PipeConnection, reduce_pipe_connection)
|
| 965 |
+
|
| 966 |
+
else:
|
| 967 |
+
def reduce_connection(conn):
|
| 968 |
+
df = reduction.DupFd(conn.fileno())
|
| 969 |
+
return rebuild_connection, (df, conn.readable, conn.writable)
|
| 970 |
+
def rebuild_connection(df, readable, writable):
|
| 971 |
+
fd = df.detach()
|
| 972 |
+
return Connection(fd, readable, writable)
|
| 973 |
+
reduction.register(Connection, reduce_connection)
|
miniconda3/envs/ladir/lib/python3.10/multiprocessing/context.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import threading
|
| 4 |
+
|
| 5 |
+
from . import process
|
| 6 |
+
from . import reduction
|
| 7 |
+
|
| 8 |
+
__all__ = ()
|
| 9 |
+
|
| 10 |
+
#
|
| 11 |
+
# Exceptions
|
| 12 |
+
#
|
| 13 |
+
|
| 14 |
+
class ProcessError(Exception):
|
| 15 |
+
pass
|
| 16 |
+
|
| 17 |
+
class BufferTooShort(ProcessError):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
class TimeoutError(ProcessError):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
class AuthenticationError(ProcessError):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
#
|
| 27 |
+
# Base type for contexts. Bound methods of an instance of this type are included in __all__ of __init__.py
|
| 28 |
+
#
|
| 29 |
+
|
| 30 |
+
class BaseContext(object):
|
| 31 |
+
|
| 32 |
+
ProcessError = ProcessError
|
| 33 |
+
BufferTooShort = BufferTooShort
|
| 34 |
+
TimeoutError = TimeoutError
|
| 35 |
+
AuthenticationError = AuthenticationError
|
| 36 |
+
|
| 37 |
+
current_process = staticmethod(process.current_process)
|
| 38 |
+
parent_process = staticmethod(process.parent_process)
|
| 39 |
+
active_children = staticmethod(process.active_children)
|
| 40 |
+
|
| 41 |
+
def cpu_count(self):
|
| 42 |
+
'''Returns the number of CPUs in the system'''
|
| 43 |
+
num = os.cpu_count()
|
| 44 |
+
if num is None:
|
| 45 |
+
raise NotImplementedError('cannot determine number of cpus')
|
| 46 |
+
else:
|
| 47 |
+
return num
|
| 48 |
+
|
| 49 |
+
def Manager(self):
|
| 50 |
+
'''Returns a manager associated with a running server process
|
| 51 |
+
|
| 52 |
+
The managers methods such as `Lock()`, `Condition()` and `Queue()`
|
| 53 |
+
can be used to create shared objects.
|
| 54 |
+
'''
|
| 55 |
+
from .managers import SyncManager
|
| 56 |
+
m = SyncManager(ctx=self.get_context())
|
| 57 |
+
m.start()
|
| 58 |
+
return m
|
| 59 |
+
|
| 60 |
+
def Pipe(self, duplex=True):
|
| 61 |
+
'''Returns two connection object connected by a pipe'''
|
| 62 |
+
from .connection import Pipe
|
| 63 |
+
return Pipe(duplex)
|
| 64 |
+
|
| 65 |
+
def Lock(self):
|
| 66 |
+
'''Returns a non-recursive lock object'''
|
| 67 |
+
from .synchronize import Lock
|
| 68 |
+
return Lock(ctx=self.get_context())
|
| 69 |
+
|
| 70 |
+
def RLock(self):
|
| 71 |
+
'''Returns a recursive lock object'''
|
| 72 |
+
from .synchronize import RLock
|
| 73 |
+
return RLock(ctx=self.get_context())
|
| 74 |
+
|
| 75 |
+
def Condition(self, lock=None):
|
| 76 |
+
'''Returns a condition object'''
|
| 77 |
+
from .synchronize import Condition
|
| 78 |
+
return Condition(lock, ctx=self.get_context())
|
| 79 |
+
|
| 80 |
+
def Semaphore(self, value=1):
|
| 81 |
+
'''Returns a semaphore object'''
|
| 82 |
+
from .synchronize import Semaphore
|
| 83 |
+
return Semaphore(value, ctx=self.get_context())
|
| 84 |
+
|
| 85 |
+
def BoundedSemaphore(self, value=1):
|
| 86 |
+
'''Returns a bounded semaphore object'''
|
| 87 |
+
from .synchronize import BoundedSemaphore
|
| 88 |
+
return BoundedSemaphore(value, ctx=self.get_context())
|
| 89 |
+
|
| 90 |
+
def Event(self):
|
| 91 |
+
'''Returns an event object'''
|
| 92 |
+
from .synchronize import Event
|
| 93 |
+
return Event(ctx=self.get_context())
|
| 94 |
+
|
| 95 |
+
def Barrier(self, parties, action=None, timeout=None):
|
| 96 |
+
'''Returns a barrier object'''
|
| 97 |
+
from .synchronize import Barrier
|
| 98 |
+
return Barrier(parties, action, timeout, ctx=self.get_context())
|
| 99 |
+
|
| 100 |
+
def Queue(self, maxsize=0):
|
| 101 |
+
'''Returns a queue object'''
|
| 102 |
+
from .queues import Queue
|
| 103 |
+
return Queue(maxsize, ctx=self.get_context())
|
| 104 |
+
|
| 105 |
+
def JoinableQueue(self, maxsize=0):
|
| 106 |
+
'''Returns a queue object'''
|
| 107 |
+
from .queues import JoinableQueue
|
| 108 |
+
return JoinableQueue(maxsize, ctx=self.get_context())
|
| 109 |
+
|
| 110 |
+
def SimpleQueue(self):
|
| 111 |
+
'''Returns a queue object'''
|
| 112 |
+
from .queues import SimpleQueue
|
| 113 |
+
return SimpleQueue(ctx=self.get_context())
|
| 114 |
+
|
| 115 |
+
def Pool(self, processes=None, initializer=None, initargs=(),
|
| 116 |
+
maxtasksperchild=None):
|
| 117 |
+
'''Returns a process pool object'''
|
| 118 |
+
from .pool import Pool
|
| 119 |
+
return Pool(processes, initializer, initargs, maxtasksperchild,
|
| 120 |
+
context=self.get_context())
|
| 121 |
+
|
| 122 |
+
def RawValue(self, typecode_or_type, *args):
|
| 123 |
+
'''Returns a shared object'''
|
| 124 |
+
from .sharedctypes import RawValue
|
| 125 |
+
return RawValue(typecode_or_type, *args)
|
| 126 |
+
|
| 127 |
+
def RawArray(self, typecode_or_type, size_or_initializer):
|
| 128 |
+
'''Returns a shared array'''
|
| 129 |
+
from .sharedctypes import RawArray
|
| 130 |
+
return RawArray(typecode_or_type, size_or_initializer)
|
| 131 |
+
|
| 132 |
+
def Value(self, typecode_or_type, *args, lock=True):
|
| 133 |
+
'''Returns a synchronized shared object'''
|
| 134 |
+
from .sharedctypes import Value
|
| 135 |
+
return Value(typecode_or_type, *args, lock=lock,
|
| 136 |
+
ctx=self.get_context())
|
| 137 |
+
|
| 138 |
+
def Array(self, typecode_or_type, size_or_initializer, *, lock=True):
|
| 139 |
+
'''Returns a synchronized shared array'''
|
| 140 |
+
from .sharedctypes import Array
|
| 141 |
+
return Array(typecode_or_type, size_or_initializer, lock=lock,
|
| 142 |
+
ctx=self.get_context())
|
| 143 |
+
|
| 144 |
+
def freeze_support(self):
|
| 145 |
+
'''Check whether this is a fake forked process in a frozen executable.
|
| 146 |
+
If so then run code specified by commandline and exit.
|
| 147 |
+
'''
|
| 148 |
+
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
|
| 149 |
+
from .spawn import freeze_support
|
| 150 |
+
freeze_support()
|
| 151 |
+
|
| 152 |
+
def get_logger(self):
|
| 153 |
+
'''Return package logger -- if it does not already exist then
|
| 154 |
+
it is created.
|
| 155 |
+
'''
|
| 156 |
+
from .util import get_logger
|
| 157 |
+
return get_logger()
|
| 158 |
+
|
| 159 |
+
def log_to_stderr(self, level=None):
|
| 160 |
+
'''Turn on logging and add a handler which prints to stderr'''
|
| 161 |
+
from .util import log_to_stderr
|
| 162 |
+
return log_to_stderr(level)
|
| 163 |
+
|
| 164 |
+
def allow_connection_pickling(self):
|
| 165 |
+
'''Install support for sending connections and sockets
|
| 166 |
+
between processes
|
| 167 |
+
'''
|
| 168 |
+
# This is undocumented. In previous versions of multiprocessing
|
| 169 |
+
# its only effect was to make socket objects inheritable on Windows.
|
| 170 |
+
from . import connection
|
| 171 |
+
|
| 172 |
+
def set_executable(self, executable):
|
| 173 |
+
'''Sets the path to a python.exe or pythonw.exe binary used to run
|
| 174 |
+
child processes instead of sys.executable when using the 'spawn'
|
| 175 |
+
start method. Useful for people embedding Python.
|
| 176 |
+
'''
|
| 177 |
+
from .spawn import set_executable
|
| 178 |
+
set_executable(executable)
|
| 179 |
+
|
| 180 |
+
def set_forkserver_preload(self, module_names):
|
| 181 |
+
'''Set list of module names to try to load in forkserver process.
|
| 182 |
+
This is really just a hint.
|
| 183 |
+
'''
|
| 184 |
+
from .forkserver import set_forkserver_preload
|
| 185 |
+
set_forkserver_preload(module_names)
|
| 186 |
+
|
| 187 |
+
def get_context(self, method=None):
|
| 188 |
+
if method is None:
|
| 189 |
+
return self
|
| 190 |
+
try:
|
| 191 |
+
ctx = _concrete_contexts[method]
|
| 192 |
+
except KeyError:
|
| 193 |
+
raise ValueError('cannot find context for %r' % method) from None
|
| 194 |
+
ctx._check_available()
|
| 195 |
+
return ctx
|
| 196 |
+
|
| 197 |
+
def get_start_method(self, allow_none=False):
|
| 198 |
+
return self._name
|
| 199 |
+
|
| 200 |
+
def set_start_method(self, method, force=False):
|
| 201 |
+
raise ValueError('cannot set start method of concrete context')
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def reducer(self):
|
| 205 |
+
'''Controls how objects will be reduced to a form that can be
|
| 206 |
+
shared with other processes.'''
|
| 207 |
+
return globals().get('reduction')
|
| 208 |
+
|
| 209 |
+
@reducer.setter
|
| 210 |
+
def reducer(self, reduction):
|
| 211 |
+
globals()['reduction'] = reduction
|
| 212 |
+
|
| 213 |
+
def _check_available(self):
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
#
|
| 217 |
+
# Type of default context -- underlying context can be set at most once
|
| 218 |
+
#
|
| 219 |
+
|
| 220 |
+
class Process(process.BaseProcess):
|
| 221 |
+
_start_method = None
|
| 222 |
+
@staticmethod
|
| 223 |
+
def _Popen(process_obj):
|
| 224 |
+
return _default_context.get_context().Process._Popen(process_obj)
|
| 225 |
+
|
| 226 |
+
@staticmethod
|
| 227 |
+
def _after_fork():
|
| 228 |
+
return _default_context.get_context().Process._after_fork()
|
| 229 |
+
|
| 230 |
+
class DefaultContext(BaseContext):
|
| 231 |
+
Process = Process
|
| 232 |
+
|
| 233 |
+
def __init__(self, context):
|
| 234 |
+
self._default_context = context
|
| 235 |
+
self._actual_context = None
|
| 236 |
+
|
| 237 |
+
def get_context(self, method=None):
|
| 238 |
+
if method is None:
|
| 239 |
+
if self._actual_context is None:
|
| 240 |
+
self._actual_context = self._default_context
|
| 241 |
+
return self._actual_context
|
| 242 |
+
else:
|
| 243 |
+
return super().get_context(method)
|
| 244 |
+
|
| 245 |
+
def set_start_method(self, method, force=False):
|
| 246 |
+
if self._actual_context is not None and not force:
|
| 247 |
+
raise RuntimeError('context has already been set')
|
| 248 |
+
if method is None and force:
|
| 249 |
+
self._actual_context = None
|
| 250 |
+
return
|
| 251 |
+
self._actual_context = self.get_context(method)
|
| 252 |
+
|
| 253 |
+
def get_start_method(self, allow_none=False):
|
| 254 |
+
if self._actual_context is None:
|
| 255 |
+
if allow_none:
|
| 256 |
+
return None
|
| 257 |
+
self._actual_context = self._default_context
|
| 258 |
+
return self._actual_context._name
|
| 259 |
+
|
| 260 |
+
def get_all_start_methods(self):
|
| 261 |
+
if sys.platform == 'win32':
|
| 262 |
+
return ['spawn']
|
| 263 |
+
else:
|
| 264 |
+
methods = ['spawn', 'fork'] if sys.platform == 'darwin' else ['fork', 'spawn']
|
| 265 |
+
if reduction.HAVE_SEND_HANDLE:
|
| 266 |
+
methods.append('forkserver')
|
| 267 |
+
return methods
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
#
|
| 271 |
+
# Context types for fixed start method
|
| 272 |
+
#
|
| 273 |
+
|
| 274 |
+
if sys.platform != 'win32':
|
| 275 |
+
|
| 276 |
+
class ForkProcess(process.BaseProcess):
|
| 277 |
+
_start_method = 'fork'
|
| 278 |
+
@staticmethod
|
| 279 |
+
def _Popen(process_obj):
|
| 280 |
+
from .popen_fork import Popen
|
| 281 |
+
return Popen(process_obj)
|
| 282 |
+
|
| 283 |
+
class SpawnProcess(process.BaseProcess):
|
| 284 |
+
_start_method = 'spawn'
|
| 285 |
+
@staticmethod
|
| 286 |
+
def _Popen(process_obj):
|
| 287 |
+
from .popen_spawn_posix import Popen
|
| 288 |
+
return Popen(process_obj)
|
| 289 |
+
|
| 290 |
+
@staticmethod
|
| 291 |
+
def _after_fork():
|
| 292 |
+
# process is spawned, nothing to do
|
| 293 |
+
pass
|
| 294 |
+
|
| 295 |
+
class ForkServerProcess(process.BaseProcess):
|
| 296 |
+
_start_method = 'forkserver'
|
| 297 |
+
@staticmethod
|
| 298 |
+
def _Popen(process_obj):
|
| 299 |
+
from .popen_forkserver import Popen
|
| 300 |
+
return Popen(process_obj)
|
| 301 |
+
|
| 302 |
+
class ForkContext(BaseContext):
|
| 303 |
+
_name = 'fork'
|
| 304 |
+
Process = ForkProcess
|
| 305 |
+
|
| 306 |
+
class SpawnContext(BaseContext):
|
| 307 |
+
_name = 'spawn'
|
| 308 |
+
Process = SpawnProcess
|
| 309 |
+
|
| 310 |
+
class ForkServerContext(BaseContext):
|
| 311 |
+
_name = 'forkserver'
|
| 312 |
+
Process = ForkServerProcess
|
| 313 |
+
def _check_available(self):
|
| 314 |
+
if not reduction.HAVE_SEND_HANDLE:
|
| 315 |
+
raise ValueError('forkserver start method not available')
|
| 316 |
+
|
| 317 |
+
_concrete_contexts = {
|
| 318 |
+
'fork': ForkContext(),
|
| 319 |
+
'spawn': SpawnContext(),
|
| 320 |
+
'forkserver': ForkServerContext(),
|
| 321 |
+
}
|
| 322 |
+
if sys.platform == 'darwin':
|
| 323 |
+
# bpo-33725: running arbitrary code after fork() is no longer reliable
|
| 324 |
+
# on macOS since macOS 10.14 (Mojave). Use spawn by default instead.
|
| 325 |
+
_default_context = DefaultContext(_concrete_contexts['spawn'])
|
| 326 |
+
else:
|
| 327 |
+
_default_context = DefaultContext(_concrete_contexts['fork'])
|
| 328 |
+
|
| 329 |
+
else:
|
| 330 |
+
|
| 331 |
+
class SpawnProcess(process.BaseProcess):
|
| 332 |
+
_start_method = 'spawn'
|
| 333 |
+
@staticmethod
|
| 334 |
+
def _Popen(process_obj):
|
| 335 |
+
from .popen_spawn_win32 import Popen
|
| 336 |
+
return Popen(process_obj)
|
| 337 |
+
|
| 338 |
+
@staticmethod
|
| 339 |
+
def _after_fork():
|
| 340 |
+
# process is spawned, nothing to do
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
class SpawnContext(BaseContext):
|
| 344 |
+
_name = 'spawn'
|
| 345 |
+
Process = SpawnProcess
|
| 346 |
+
|
| 347 |
+
_concrete_contexts = {
|
| 348 |
+
'spawn': SpawnContext(),
|
| 349 |
+
}
|
| 350 |
+
_default_context = DefaultContext(_concrete_contexts['spawn'])
|
| 351 |
+
|
| 352 |
+
#
|
| 353 |
+
# Force the start method
|
| 354 |
+
#
|
| 355 |
+
|
| 356 |
+
def _force_start_method(method):
|
| 357 |
+
_default_context._actual_context = _concrete_contexts[method]
|
| 358 |
+
|
| 359 |
+
#
|
| 360 |
+
# Check that the current thread is spawning a child process
|
| 361 |
+
#
|
| 362 |
+
|
| 363 |
+
_tls = threading.local()
|
| 364 |
+
|
| 365 |
+
def get_spawning_popen():
|
| 366 |
+
return getattr(_tls, 'spawning_popen', None)
|
| 367 |
+
|
| 368 |
+
def set_spawning_popen(popen):
|
| 369 |
+
_tls.spawning_popen = popen
|
| 370 |
+
|
| 371 |
+
def assert_spawning(obj):
|
| 372 |
+
if get_spawning_popen() is None:
|
| 373 |
+
raise RuntimeError(
|
| 374 |
+
'%s objects should only be shared between processes'
|
| 375 |
+
' through inheritance' % type(obj).__name__
|
| 376 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/multiprocessing/dummy/__init__.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Support for the API of the multiprocessing package using threads
|
| 3 |
+
#
|
| 4 |
+
# multiprocessing/dummy/__init__.py
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 7 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 8 |
+
#
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
'Process', 'current_process', 'active_children', 'freeze_support',
|
| 12 |
+
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
|
| 13 |
+
'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue'
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
#
|
| 17 |
+
# Imports
|
| 18 |
+
#
|
| 19 |
+
|
| 20 |
+
import threading
|
| 21 |
+
import sys
|
| 22 |
+
import weakref
|
| 23 |
+
import array
|
| 24 |
+
|
| 25 |
+
from .connection import Pipe
|
| 26 |
+
from threading import Lock, RLock, Semaphore, BoundedSemaphore
|
| 27 |
+
from threading import Event, Condition, Barrier
|
| 28 |
+
from queue import Queue
|
| 29 |
+
|
| 30 |
+
#
|
| 31 |
+
#
|
| 32 |
+
#
|
| 33 |
+
|
| 34 |
+
class DummyProcess(threading.Thread):
|
| 35 |
+
|
| 36 |
+
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
|
| 37 |
+
threading.Thread.__init__(self, group, target, name, args, kwargs)
|
| 38 |
+
self._pid = None
|
| 39 |
+
self._children = weakref.WeakKeyDictionary()
|
| 40 |
+
self._start_called = False
|
| 41 |
+
self._parent = current_process()
|
| 42 |
+
|
| 43 |
+
def start(self):
|
| 44 |
+
if self._parent is not current_process():
|
| 45 |
+
raise RuntimeError(
|
| 46 |
+
"Parent is {0!r} but current_process is {1!r}".format(
|
| 47 |
+
self._parent, current_process()))
|
| 48 |
+
self._start_called = True
|
| 49 |
+
if hasattr(self._parent, '_children'):
|
| 50 |
+
self._parent._children[self] = None
|
| 51 |
+
threading.Thread.start(self)
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def exitcode(self):
|
| 55 |
+
if self._start_called and not self.is_alive():
|
| 56 |
+
return 0
|
| 57 |
+
else:
|
| 58 |
+
return None
|
| 59 |
+
|
| 60 |
+
#
|
| 61 |
+
#
|
| 62 |
+
#
|
| 63 |
+
|
| 64 |
+
Process = DummyProcess
|
| 65 |
+
current_process = threading.current_thread
|
| 66 |
+
current_process()._children = weakref.WeakKeyDictionary()
|
| 67 |
+
|
| 68 |
+
def active_children():
|
| 69 |
+
children = current_process()._children
|
| 70 |
+
for p in list(children):
|
| 71 |
+
if not p.is_alive():
|
| 72 |
+
children.pop(p, None)
|
| 73 |
+
return list(children)
|
| 74 |
+
|
| 75 |
+
def freeze_support():
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
#
|
| 79 |
+
#
|
| 80 |
+
#
|
| 81 |
+
|
| 82 |
+
class Namespace(object):
|
| 83 |
+
def __init__(self, /, **kwds):
|
| 84 |
+
self.__dict__.update(kwds)
|
| 85 |
+
def __repr__(self):
|
| 86 |
+
items = list(self.__dict__.items())
|
| 87 |
+
temp = []
|
| 88 |
+
for name, value in items:
|
| 89 |
+
if not name.startswith('_'):
|
| 90 |
+
temp.append('%s=%r' % (name, value))
|
| 91 |
+
temp.sort()
|
| 92 |
+
return '%s(%s)' % (self.__class__.__name__, ', '.join(temp))
|
| 93 |
+
|
| 94 |
+
dict = dict
|
| 95 |
+
list = list
|
| 96 |
+
|
| 97 |
+
def Array(typecode, sequence, lock=True):
|
| 98 |
+
return array.array(typecode, sequence)
|
| 99 |
+
|
| 100 |
+
class Value(object):
|
| 101 |
+
def __init__(self, typecode, value, lock=True):
|
| 102 |
+
self._typecode = typecode
|
| 103 |
+
self._value = value
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def value(self):
|
| 107 |
+
return self._value
|
| 108 |
+
|
| 109 |
+
@value.setter
|
| 110 |
+
def value(self, value):
|
| 111 |
+
self._value = value
|
| 112 |
+
|
| 113 |
+
def __repr__(self):
|
| 114 |
+
return '<%s(%r, %r)>'%(type(self).__name__,self._typecode,self._value)
|
| 115 |
+
|
| 116 |
+
def Manager():
|
| 117 |
+
return sys.modules[__name__]
|
| 118 |
+
|
| 119 |
+
def shutdown():
|
| 120 |
+
pass
|
| 121 |
+
|
| 122 |
+
def Pool(processes=None, initializer=None, initargs=()):
|
| 123 |
+
from ..pool import ThreadPool
|
| 124 |
+
return ThreadPool(processes, initializer, initargs)
|
| 125 |
+
|
| 126 |
+
JoinableQueue = Queue
|
miniconda3/envs/ladir/lib/python3.10/multiprocessing/dummy/connection.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Analogue of `multiprocessing.connection` which uses queues instead of sockets
|
| 3 |
+
#
|
| 4 |
+
# multiprocessing/dummy/connection.py
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 7 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 8 |
+
#
|
| 9 |
+
|
| 10 |
+
__all__ = [ 'Client', 'Listener', 'Pipe' ]
|
| 11 |
+
|
| 12 |
+
from queue import Queue
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
families = [None]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Listener(object):
|
| 19 |
+
|
| 20 |
+
def __init__(self, address=None, family=None, backlog=1):
|
| 21 |
+
self._backlog_queue = Queue(backlog)
|
| 22 |
+
|
| 23 |
+
def accept(self):
|
| 24 |
+
return Connection(*self._backlog_queue.get())
|
| 25 |
+
|
| 26 |
+
def close(self):
|
| 27 |
+
self._backlog_queue = None
|
| 28 |
+
|
| 29 |
+
@property
|
| 30 |
+
def address(self):
|
| 31 |
+
return self._backlog_queue
|
| 32 |
+
|
| 33 |
+
def __enter__(self):
|
| 34 |
+
return self
|
| 35 |
+
|
| 36 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
| 37 |
+
self.close()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def Client(address):
|
| 41 |
+
_in, _out = Queue(), Queue()
|
| 42 |
+
address.put((_out, _in))
|
| 43 |
+
return Connection(_in, _out)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def Pipe(duplex=True):
|
| 47 |
+
a, b = Queue(), Queue()
|
| 48 |
+
return Connection(a, b), Connection(b, a)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Connection(object):
|
| 52 |
+
|
| 53 |
+
def __init__(self, _in, _out):
|
| 54 |
+
self._out = _out
|
| 55 |
+
self._in = _in
|
| 56 |
+
self.send = self.send_bytes = _out.put
|
| 57 |
+
self.recv = self.recv_bytes = _in.get
|
| 58 |
+
|
| 59 |
+
def poll(self, timeout=0.0):
|
| 60 |
+
if self._in.qsize() > 0:
|
| 61 |
+
return True
|
| 62 |
+
if timeout <= 0.0:
|
| 63 |
+
return False
|
| 64 |
+
with self._in.not_empty:
|
| 65 |
+
self._in.not_empty.wait(timeout)
|
| 66 |
+
return self._in.qsize() > 0
|
| 67 |
+
|
| 68 |
+
def close(self):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
def __enter__(self):
|
| 72 |
+
return self
|
| 73 |
+
|
| 74 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
| 75 |
+
self.close()
|
miniconda3/envs/ladir/lib/python3.10/multipr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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import errno
|
| 2 |
+
import os
|
| 3 |
+
import selectors
|
| 4 |
+
import signal
|
| 5 |
+
import socket
|
| 6 |
+
import struct
|
| 7 |
+
import sys
|
| 8 |
+
import threading
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
from . import connection
|
| 12 |
+
from . import process
|
| 13 |
+
from .context import reduction
|
| 14 |
+
from . import resource_tracker
|
| 15 |
+
from . import spawn
|
| 16 |
+
from . import util
|
| 17 |
+
|
| 18 |
+
__all__ = ['ensure_running', 'get_inherited_fds', 'connect_to_new_process',
|
| 19 |
+
'set_forkserver_preload']
|
| 20 |
+
|
| 21 |
+
#
|
| 22 |
+
#
|
| 23 |
+
#
|
| 24 |
+
|
| 25 |
+
MAXFDS_TO_SEND = 256
|
| 26 |
+
SIGNED_STRUCT = struct.Struct('q') # large enough for pid_t
|
| 27 |
+
|
| 28 |
+
#
|
| 29 |
+
# Forkserver class
|
| 30 |
+
#
|
| 31 |
+
|
| 32 |
+
class ForkServer(object):
|
| 33 |
+
|
| 34 |
+
def __init__(self):
|
| 35 |
+
self._forkserver_address = None
|
| 36 |
+
self._forkserver_alive_fd = None
|
| 37 |
+
self._forkserver_pid = None
|
| 38 |
+
self._inherited_fds = None
|
| 39 |
+
self._lock = threading.Lock()
|
| 40 |
+
self._preload_modules = ['__main__']
|
| 41 |
+
|
| 42 |
+
def _stop(self):
|
| 43 |
+
# Method used by unit tests to stop the server
|
| 44 |
+
with self._lock:
|
| 45 |
+
self._stop_unlocked()
|
| 46 |
+
|
| 47 |
+
def _stop_unlocked(self):
|
| 48 |
+
if self._forkserver_pid is None:
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
# close the "alive" file descriptor asks the server to stop
|
| 52 |
+
os.close(self._forkserver_alive_fd)
|
| 53 |
+
self._forkserver_alive_fd = None
|
| 54 |
+
|
| 55 |
+
os.waitpid(self._forkserver_pid, 0)
|
| 56 |
+
self._forkserver_pid = None
|
| 57 |
+
|
| 58 |
+
if not util.is_abstract_socket_namespace(self._forkserver_address):
|
| 59 |
+
os.unlink(self._forkserver_address)
|
| 60 |
+
self._forkserver_address = None
|
| 61 |
+
|
| 62 |
+
def set_forkserver_preload(self, modules_names):
|
| 63 |
+
'''Set list of module names to try to load in forkserver process.'''
|
| 64 |
+
if not all(type(mod) is str for mod in self._preload_modules):
|
| 65 |
+
raise TypeError('module_names must be a list of strings')
|
| 66 |
+
self._preload_modules = modules_names
|
| 67 |
+
|
| 68 |
+
def get_inherited_fds(self):
|
| 69 |
+
'''Return list of fds inherited from parent process.
|
| 70 |
+
|
| 71 |
+
This returns None if the current process was not started by fork
|
| 72 |
+
server.
|
| 73 |
+
'''
|
| 74 |
+
return self._inherited_fds
|
| 75 |
+
|
| 76 |
+
def connect_to_new_process(self, fds):
|
| 77 |
+
'''Request forkserver to create a child process.
|
| 78 |
+
|
| 79 |
+
Returns a pair of fds (status_r, data_w). The calling process can read
|
| 80 |
+
the child process's pid and (eventually) its returncode from status_r.
|
| 81 |
+
The calling process should write to data_w the pickled preparation and
|
| 82 |
+
process data.
|
| 83 |
+
'''
|
| 84 |
+
self.ensure_running()
|
| 85 |
+
if len(fds) + 4 >= MAXFDS_TO_SEND:
|
| 86 |
+
raise ValueError('too many fds')
|
| 87 |
+
with socket.socket(socket.AF_UNIX) as client:
|
| 88 |
+
client.connect(self._forkserver_address)
|
| 89 |
+
parent_r, child_w = os.pipe()
|
| 90 |
+
child_r, parent_w = os.pipe()
|
| 91 |
+
allfds = [child_r, child_w, self._forkserver_alive_fd,
|
| 92 |
+
resource_tracker.getfd()]
|
| 93 |
+
allfds += fds
|
| 94 |
+
try:
|
| 95 |
+
reduction.sendfds(client, allfds)
|
| 96 |
+
return parent_r, parent_w
|
| 97 |
+
except:
|
| 98 |
+
os.close(parent_r)
|
| 99 |
+
os.close(parent_w)
|
| 100 |
+
raise
|
| 101 |
+
finally:
|
| 102 |
+
os.close(child_r)
|
| 103 |
+
os.close(child_w)
|
| 104 |
+
|
| 105 |
+
def ensure_running(self):
|
| 106 |
+
'''Make sure that a fork server is running.
|
| 107 |
+
|
| 108 |
+
This can be called from any process. Note that usually a child
|
| 109 |
+
process will just reuse the forkserver started by its parent, so
|
| 110 |
+
ensure_running() will do nothing.
|
| 111 |
+
'''
|
| 112 |
+
with self._lock:
|
| 113 |
+
resource_tracker.ensure_running()
|
| 114 |
+
if self._forkserver_pid is not None:
|
| 115 |
+
# forkserver was launched before, is it still running?
|
| 116 |
+
pid, status = os.waitpid(self._forkserver_pid, os.WNOHANG)
|
| 117 |
+
if not pid:
|
| 118 |
+
# still alive
|
| 119 |
+
return
|
| 120 |
+
# dead, launch it again
|
| 121 |
+
os.close(self._forkserver_alive_fd)
|
| 122 |
+
self._forkserver_address = None
|
| 123 |
+
self._forkserver_alive_fd = None
|
| 124 |
+
self._forkserver_pid = None
|
| 125 |
+
|
| 126 |
+
cmd = ('from multiprocessing.forkserver import main; ' +
|
| 127 |
+
'main(%d, %d, %r, **%r)')
|
| 128 |
+
|
| 129 |
+
if self._preload_modules:
|
| 130 |
+
desired_keys = {'main_path', 'sys_path'}
|
| 131 |
+
data = spawn.get_preparation_data('ignore')
|
| 132 |
+
data = {x: y for x, y in data.items() if x in desired_keys}
|
| 133 |
+
else:
|
| 134 |
+
data = {}
|
| 135 |
+
|
| 136 |
+
with socket.socket(socket.AF_UNIX) as listener:
|
| 137 |
+
address = connection.arbitrary_address('AF_UNIX')
|
| 138 |
+
listener.bind(address)
|
| 139 |
+
if not util.is_abstract_socket_namespace(address):
|
| 140 |
+
os.chmod(address, 0o600)
|
| 141 |
+
listener.listen()
|
| 142 |
+
|
| 143 |
+
# all client processes own the write end of the "alive" pipe;
|
| 144 |
+
# when they all terminate the read end becomes ready.
|
| 145 |
+
alive_r, alive_w = os.pipe()
|
| 146 |
+
try:
|
| 147 |
+
fds_to_pass = [listener.fileno(), alive_r]
|
| 148 |
+
cmd %= (listener.fileno(), alive_r, self._preload_modules,
|
| 149 |
+
data)
|
| 150 |
+
exe = spawn.get_executable()
|
| 151 |
+
args = [exe] + util._args_from_interpreter_flags()
|
| 152 |
+
args += ['-c', cmd]
|
| 153 |
+
pid = util.spawnv_passfds(exe, args, fds_to_pass)
|
| 154 |
+
except:
|
| 155 |
+
os.close(alive_w)
|
| 156 |
+
raise
|
| 157 |
+
finally:
|
| 158 |
+
os.close(alive_r)
|
| 159 |
+
self._forkserver_address = address
|
| 160 |
+
self._forkserver_alive_fd = alive_w
|
| 161 |
+
self._forkserver_pid = pid
|
| 162 |
+
|
| 163 |
+
#
|
| 164 |
+
#
|
| 165 |
+
#
|
| 166 |
+
|
| 167 |
+
def main(listener_fd, alive_r, preload, main_path=None, sys_path=None):
|
| 168 |
+
'''Run forkserver.'''
|
| 169 |
+
if preload:
|
| 170 |
+
if '__main__' in preload and main_path is not None:
|
| 171 |
+
process.current_process()._inheriting = True
|
| 172 |
+
try:
|
| 173 |
+
spawn.import_main_path(main_path)
|
| 174 |
+
finally:
|
| 175 |
+
del process.current_process()._inheriting
|
| 176 |
+
for modname in preload:
|
| 177 |
+
try:
|
| 178 |
+
__import__(modname)
|
| 179 |
+
except ImportError:
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
util._close_stdin()
|
| 183 |
+
|
| 184 |
+
sig_r, sig_w = os.pipe()
|
| 185 |
+
os.set_blocking(sig_r, False)
|
| 186 |
+
os.set_blocking(sig_w, False)
|
| 187 |
+
|
| 188 |
+
def sigchld_handler(*_unused):
|
| 189 |
+
# Dummy signal handler, doesn't do anything
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
handlers = {
|
| 193 |
+
# unblocking SIGCHLD allows the wakeup fd to notify our event loop
|
| 194 |
+
signal.SIGCHLD: sigchld_handler,
|
| 195 |
+
# protect the process from ^C
|
| 196 |
+
signal.SIGINT: signal.SIG_IGN,
|
| 197 |
+
}
|
| 198 |
+
old_handlers = {sig: signal.signal(sig, val)
|
| 199 |
+
for (sig, val) in handlers.items()}
|
| 200 |
+
|
| 201 |
+
# calling os.write() in the Python signal handler is racy
|
| 202 |
+
signal.set_wakeup_fd(sig_w)
|
| 203 |
+
|
| 204 |
+
# map child pids to client fds
|
| 205 |
+
pid_to_fd = {}
|
| 206 |
+
|
| 207 |
+
with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \
|
| 208 |
+
selectors.DefaultSelector() as selector:
|
| 209 |
+
_forkserver._forkserver_address = listener.getsockname()
|
| 210 |
+
|
| 211 |
+
selector.register(listener, selectors.EVENT_READ)
|
| 212 |
+
selector.register(alive_r, selectors.EVENT_READ)
|
| 213 |
+
selector.register(sig_r, selectors.EVENT_READ)
|
| 214 |
+
|
| 215 |
+
while True:
|
| 216 |
+
try:
|
| 217 |
+
while True:
|
| 218 |
+
rfds = [key.fileobj for (key, events) in selector.select()]
|
| 219 |
+
if rfds:
|
| 220 |
+
break
|
| 221 |
+
|
| 222 |
+
if alive_r in rfds:
|
| 223 |
+
# EOF because no more client processes left
|
| 224 |
+
assert os.read(alive_r, 1) == b'', "Not at EOF?"
|
| 225 |
+
raise SystemExit
|
| 226 |
+
|
| 227 |
+
if sig_r in rfds:
|
| 228 |
+
# Got SIGCHLD
|
| 229 |
+
os.read(sig_r, 65536) # exhaust
|
| 230 |
+
while True:
|
| 231 |
+
# Scan for child processes
|
| 232 |
+
try:
|
| 233 |
+
pid, sts = os.waitpid(-1, os.WNOHANG)
|
| 234 |
+
except ChildProcessError:
|
| 235 |
+
break
|
| 236 |
+
if pid == 0:
|
| 237 |
+
break
|
| 238 |
+
child_w = pid_to_fd.pop(pid, None)
|
| 239 |
+
if child_w is not None:
|
| 240 |
+
returncode = os.waitstatus_to_exitcode(sts)
|
| 241 |
+
|
| 242 |
+
# Send exit code to client process
|
| 243 |
+
try:
|
| 244 |
+
write_signed(child_w, returncode)
|
| 245 |
+
except BrokenPipeError:
|
| 246 |
+
# client vanished
|
| 247 |
+
pass
|
| 248 |
+
os.close(child_w)
|
| 249 |
+
else:
|
| 250 |
+
# This shouldn't happen really
|
| 251 |
+
warnings.warn('forkserver: waitpid returned '
|
| 252 |
+
'unexpected pid %d' % pid)
|
| 253 |
+
|
| 254 |
+
if listener in rfds:
|
| 255 |
+
# Incoming fork request
|
| 256 |
+
with listener.accept()[0] as s:
|
| 257 |
+
# Receive fds from client
|
| 258 |
+
fds = reduction.recvfds(s, MAXFDS_TO_SEND + 1)
|
| 259 |
+
if len(fds) > MAXFDS_TO_SEND:
|
| 260 |
+
raise RuntimeError(
|
| 261 |
+
"Too many ({0:n}) fds to send".format(
|
| 262 |
+
len(fds)))
|
| 263 |
+
child_r, child_w, *fds = fds
|
| 264 |
+
s.close()
|
| 265 |
+
pid = os.fork()
|
| 266 |
+
if pid == 0:
|
| 267 |
+
# Child
|
| 268 |
+
code = 1
|
| 269 |
+
try:
|
| 270 |
+
listener.close()
|
| 271 |
+
selector.close()
|
| 272 |
+
unused_fds = [alive_r, child_w, sig_r, sig_w]
|
| 273 |
+
unused_fds.extend(pid_to_fd.values())
|
| 274 |
+
code = _serve_one(child_r, fds,
|
| 275 |
+
unused_fds,
|
| 276 |
+
old_handlers)
|
| 277 |
+
except Exception:
|
| 278 |
+
sys.excepthook(*sys.exc_info())
|
| 279 |
+
sys.stderr.flush()
|
| 280 |
+
finally:
|
| 281 |
+
os._exit(code)
|
| 282 |
+
else:
|
| 283 |
+
# Send pid to client process
|
| 284 |
+
try:
|
| 285 |
+
write_signed(child_w, pid)
|
| 286 |
+
except BrokenPipeError:
|
| 287 |
+
# client vanished
|
| 288 |
+
pass
|
| 289 |
+
pid_to_fd[pid] = child_w
|
| 290 |
+
os.close(child_r)
|
| 291 |
+
for fd in fds:
|
| 292 |
+
os.close(fd)
|
| 293 |
+
|
| 294 |
+
except OSError as e:
|
| 295 |
+
if e.errno != errno.ECONNABORTED:
|
| 296 |
+
raise
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _serve_one(child_r, fds, unused_fds, handlers):
|
| 300 |
+
# close unnecessary stuff and reset signal handlers
|
| 301 |
+
signal.set_wakeup_fd(-1)
|
| 302 |
+
for sig, val in handlers.items():
|
| 303 |
+
signal.signal(sig, val)
|
| 304 |
+
for fd in unused_fds:
|
| 305 |
+
os.close(fd)
|
| 306 |
+
|
| 307 |
+
(_forkserver._forkserver_alive_fd,
|
| 308 |
+
resource_tracker._resource_tracker._fd,
|
| 309 |
+
*_forkserver._inherited_fds) = fds
|
| 310 |
+
|
| 311 |
+
# Run process object received over pipe
|
| 312 |
+
parent_sentinel = os.dup(child_r)
|
| 313 |
+
code = spawn._main(child_r, parent_sentinel)
|
| 314 |
+
|
| 315 |
+
return code
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
#
|
| 319 |
+
# Read and write signed numbers
|
| 320 |
+
#
|
| 321 |
+
|
| 322 |
+
def read_signed(fd):
|
| 323 |
+
data = b''
|
| 324 |
+
length = SIGNED_STRUCT.size
|
| 325 |
+
while len(data) < length:
|
| 326 |
+
s = os.read(fd, length - len(data))
|
| 327 |
+
if not s:
|
| 328 |
+
raise EOFError('unexpected EOF')
|
| 329 |
+
data += s
|
| 330 |
+
return SIGNED_STRUCT.unpack(data)[0]
|
| 331 |
+
|
| 332 |
+
def write_signed(fd, n):
|
| 333 |
+
msg = SIGNED_STRUCT.pack(n)
|
| 334 |
+
while msg:
|
| 335 |
+
nbytes = os.write(fd, msg)
|
| 336 |
+
if nbytes == 0:
|
| 337 |
+
raise RuntimeError('should not get here')
|
| 338 |
+
msg = msg[nbytes:]
|
| 339 |
+
|
| 340 |
+
#
|
| 341 |
+
#
|
| 342 |
+
#
|
| 343 |
+
|
| 344 |
+
_forkserver = ForkServer()
|
| 345 |
+
ensure_running = _forkserver.ensure_running
|
| 346 |
+
get_inherited_fds = _forkserver.get_inherited_fds
|
| 347 |
+
connect_to_new_process = _forkserver.connect_to_new_process
|
| 348 |
+
set_forkserver_preload =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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Module which supports allocation of memory from an mmap
|
| 3 |
+
#
|
| 4 |
+
# multiprocessing/heap.py
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 7 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 8 |
+
#
|
| 9 |
+
|
| 10 |
+
import bisect
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
import mmap
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import tempfile
|
| 16 |
+
import threading
|
| 17 |
+
|
| 18 |
+
from .context import reduction, assert_spawning
|
| 19 |
+
from . import util
|
| 20 |
+
|
| 21 |
+
__all__ = ['BufferWrapper']
|
| 22 |
+
|
| 23 |
+
#
|
| 24 |
+
# Inheritable class which wraps an mmap, and from which blocks can be allocated
|
| 25 |
+
#
|
| 26 |
+
|
| 27 |
+
if sys.platform == 'win32':
|
| 28 |
+
|
| 29 |
+
import _winapi
|
| 30 |
+
|
| 31 |
+
class Arena(object):
|
| 32 |
+
"""
|
| 33 |
+
A shared memory area backed by anonymous memory (Windows).
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
_rand = tempfile._RandomNameSequence()
|
| 37 |
+
|
| 38 |
+
def __init__(self, size):
|
| 39 |
+
self.size = size
|
| 40 |
+
for i in range(100):
|
| 41 |
+
name = 'pym-%d-%s' % (os.getpid(), next(self._rand))
|
| 42 |
+
buf = mmap.mmap(-1, size, tagname=name)
|
| 43 |
+
if _winapi.GetLastError() == 0:
|
| 44 |
+
break
|
| 45 |
+
# We have reopened a preexisting mmap.
|
| 46 |
+
buf.close()
|
| 47 |
+
else:
|
| 48 |
+
raise FileExistsError('Cannot find name for new mmap')
|
| 49 |
+
self.name = name
|
| 50 |
+
self.buffer = buf
|
| 51 |
+
self._state = (self.size, self.name)
|
| 52 |
+
|
| 53 |
+
def __getstate__(self):
|
| 54 |
+
assert_spawning(self)
|
| 55 |
+
return self._state
|
| 56 |
+
|
| 57 |
+
def __setstate__(self, state):
|
| 58 |
+
self.size, self.name = self._state = state
|
| 59 |
+
# Reopen existing mmap
|
| 60 |
+
self.buffer = mmap.mmap(-1, self.size, tagname=self.name)
|
| 61 |
+
# XXX Temporarily preventing buildbot failures while determining
|
| 62 |
+
# XXX the correct long-term fix. See issue 23060
|
| 63 |
+
#assert _winapi.GetLastError() == _winapi.ERROR_ALREADY_EXISTS
|
| 64 |
+
|
| 65 |
+
else:
|
| 66 |
+
|
| 67 |
+
class Arena(object):
|
| 68 |
+
"""
|
| 69 |
+
A shared memory area backed by a temporary file (POSIX).
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
if sys.platform == 'linux':
|
| 73 |
+
_dir_candidates = ['/dev/shm']
|
| 74 |
+
else:
|
| 75 |
+
_dir_candidates = []
|
| 76 |
+
|
| 77 |
+
def __init__(self, size, fd=-1):
|
| 78 |
+
self.size = size
|
| 79 |
+
self.fd = fd
|
| 80 |
+
if fd == -1:
|
| 81 |
+
# Arena is created anew (if fd != -1, it means we're coming
|
| 82 |
+
# from rebuild_arena() below)
|
| 83 |
+
self.fd, name = tempfile.mkstemp(
|
| 84 |
+
prefix='pym-%d-'%os.getpid(),
|
| 85 |
+
dir=self._choose_dir(size))
|
| 86 |
+
os.unlink(name)
|
| 87 |
+
util.Finalize(self, os.close, (self.fd,))
|
| 88 |
+
os.ftruncate(self.fd, size)
|
| 89 |
+
self.buffer = mmap.mmap(self.fd, self.size)
|
| 90 |
+
|
| 91 |
+
def _choose_dir(self, size):
|
| 92 |
+
# Choose a non-storage backed directory if possible,
|
| 93 |
+
# to improve performance
|
| 94 |
+
for d in self._dir_candidates:
|
| 95 |
+
st = os.statvfs(d)
|
| 96 |
+
if st.f_bavail * st.f_frsize >= size: # enough free space?
|
| 97 |
+
return d
|
| 98 |
+
return util.get_temp_dir()
|
| 99 |
+
|
| 100 |
+
def reduce_arena(a):
|
| 101 |
+
if a.fd == -1:
|
| 102 |
+
raise ValueError('Arena is unpicklable because '
|
| 103 |
+
'forking was enabled when it was created')
|
| 104 |
+
return rebuild_arena, (a.size, reduction.DupFd(a.fd))
|
| 105 |
+
|
| 106 |
+
def rebuild_arena(size, dupfd):
|
| 107 |
+
return Arena(size, dupfd.detach())
|
| 108 |
+
|
| 109 |
+
reduction.register(Arena, reduce_arena)
|
| 110 |
+
|
| 111 |
+
#
|
| 112 |
+
# Class allowing allocation of chunks of memory from arenas
|
| 113 |
+
#
|
| 114 |
+
|
| 115 |
+
class Heap(object):
|
| 116 |
+
|
| 117 |
+
# Minimum malloc() alignment
|
| 118 |
+
_alignment = 8
|
| 119 |
+
|
| 120 |
+
_DISCARD_FREE_SPACE_LARGER_THAN = 4 * 1024 ** 2 # 4 MB
|
| 121 |
+
_DOUBLE_ARENA_SIZE_UNTIL = 4 * 1024 ** 2
|
| 122 |
+
|
| 123 |
+
def __init__(self, size=mmap.PAGESIZE):
|
| 124 |
+
self._lastpid = os.getpid()
|
| 125 |
+
self._lock = threading.Lock()
|
| 126 |
+
# Current arena allocation size
|
| 127 |
+
self._size = size
|
| 128 |
+
# A sorted list of available block sizes in arenas
|
| 129 |
+
self._lengths = []
|
| 130 |
+
|
| 131 |
+
# Free block management:
|
| 132 |
+
# - map each block size to a list of `(Arena, start, stop)` blocks
|
| 133 |
+
self._len_to_seq = {}
|
| 134 |
+
# - map `(Arena, start)` tuple to the `(Arena, start, stop)` block
|
| 135 |
+
# starting at that offset
|
| 136 |
+
self._start_to_block = {}
|
| 137 |
+
# - map `(Arena, stop)` tuple to the `(Arena, start, stop)` block
|
| 138 |
+
# ending at that offset
|
| 139 |
+
self._stop_to_block = {}
|
| 140 |
+
|
| 141 |
+
# Map arenas to their `(Arena, start, stop)` blocks in use
|
| 142 |
+
self._allocated_blocks = defaultdict(set)
|
| 143 |
+
self._arenas = []
|
| 144 |
+
|
| 145 |
+
# List of pending blocks to free - see comment in free() below
|
| 146 |
+
self._pending_free_blocks = []
|
| 147 |
+
|
| 148 |
+
# Statistics
|
| 149 |
+
self._n_mallocs = 0
|
| 150 |
+
self._n_frees = 0
|
| 151 |
+
|
| 152 |
+
@staticmethod
|
| 153 |
+
def _roundup(n, alignment):
|
| 154 |
+
# alignment must be a power of 2
|
| 155 |
+
mask = alignment - 1
|
| 156 |
+
return (n + mask) & ~mask
|
| 157 |
+
|
| 158 |
+
def _new_arena(self, size):
|
| 159 |
+
# Create a new arena with at least the given *size*
|
| 160 |
+
length = self._roundup(max(self._size, size), mmap.PAGESIZE)
|
| 161 |
+
# We carve larger and larger arenas, for efficiency, until we
|
| 162 |
+
# reach a large-ish size (roughly L3 cache-sized)
|
| 163 |
+
if self._size < self._DOUBLE_ARENA_SIZE_UNTIL:
|
| 164 |
+
self._size *= 2
|
| 165 |
+
util.info('allocating a new mmap of length %d', length)
|
| 166 |
+
arena = Arena(length)
|
| 167 |
+
self._arenas.append(arena)
|
| 168 |
+
return (arena, 0, length)
|
| 169 |
+
|
| 170 |
+
def _discard_arena(self, arena):
|
| 171 |
+
# Possibly delete the given (unused) arena
|
| 172 |
+
length = arena.size
|
| 173 |
+
# Reusing an existing arena is faster than creating a new one, so
|
| 174 |
+
# we only reclaim space if it's large enough.
|
| 175 |
+
if length < self._DISCARD_FREE_SPACE_LARGER_THAN:
|
| 176 |
+
return
|
| 177 |
+
blocks = self._allocated_blocks.pop(arena)
|
| 178 |
+
assert not blocks
|
| 179 |
+
del self._start_to_block[(arena, 0)]
|
| 180 |
+
del self._stop_to_block[(arena, length)]
|
| 181 |
+
self._arenas.remove(arena)
|
| 182 |
+
seq = self._len_to_seq[length]
|
| 183 |
+
seq.remove((arena, 0, length))
|
| 184 |
+
if not seq:
|
| 185 |
+
del self._len_to_seq[length]
|
| 186 |
+
self._lengths.remove(length)
|
| 187 |
+
|
| 188 |
+
def _malloc(self, size):
|
| 189 |
+
# returns a large enough block -- it might be much larger
|
| 190 |
+
i = bisect.bisect_left(self._lengths, size)
|
| 191 |
+
if i == len(self._lengths):
|
| 192 |
+
return self._new_arena(size)
|
| 193 |
+
else:
|
| 194 |
+
length = self._lengths[i]
|
| 195 |
+
seq = self._len_to_seq[length]
|
| 196 |
+
block = seq.pop()
|
| 197 |
+
if not seq:
|
| 198 |
+
del self._len_to_seq[length], self._lengths[i]
|
| 199 |
+
|
| 200 |
+
(arena, start, stop) = block
|
| 201 |
+
del self._start_to_block[(arena, start)]
|
| 202 |
+
del self._stop_to_block[(arena, stop)]
|
| 203 |
+
return block
|
| 204 |
+
|
| 205 |
+
def _add_free_block(self, block):
|
| 206 |
+
# make block available and try to merge with its neighbours in the arena
|
| 207 |
+
(arena, start, stop) = block
|
| 208 |
+
|
| 209 |
+
try:
|
| 210 |
+
prev_block = self._stop_to_block[(arena, start)]
|
| 211 |
+
except KeyError:
|
| 212 |
+
pass
|
| 213 |
+
else:
|
| 214 |
+
start, _ = self._absorb(prev_block)
|
| 215 |
+
|
| 216 |
+
try:
|
| 217 |
+
next_block = self._start_to_block[(arena, stop)]
|
| 218 |
+
except KeyError:
|
| 219 |
+
pass
|
| 220 |
+
else:
|
| 221 |
+
_, stop = self._absorb(next_block)
|
| 222 |
+
|
| 223 |
+
block = (arena, start, stop)
|
| 224 |
+
length = stop - start
|
| 225 |
+
|
| 226 |
+
try:
|
| 227 |
+
self._len_to_seq[length].append(block)
|
| 228 |
+
except KeyError:
|
| 229 |
+
self._len_to_seq[length] = [block]
|
| 230 |
+
bisect.insort(self._lengths, length)
|
| 231 |
+
|
| 232 |
+
self._start_to_block[(arena, start)] = block
|
| 233 |
+
self._stop_to_block[(arena, stop)] = block
|
| 234 |
+
|
| 235 |
+
def _absorb(self, block):
|
| 236 |
+
# deregister this block so it can be merged with a neighbour
|
| 237 |
+
(arena, start, stop) = block
|
| 238 |
+
del self._start_to_block[(arena, start)]
|
| 239 |
+
del self._stop_to_block[(arena, stop)]
|
| 240 |
+
|
| 241 |
+
length = stop - start
|
| 242 |
+
seq = self._len_to_seq[length]
|
| 243 |
+
seq.remove(block)
|
| 244 |
+
if not seq:
|
| 245 |
+
del self._len_to_seq[length]
|
| 246 |
+
self._lengths.remove(length)
|
| 247 |
+
|
| 248 |
+
return start, stop
|
| 249 |
+
|
| 250 |
+
def _remove_allocated_block(self, block):
|
| 251 |
+
arena, start, stop = block
|
| 252 |
+
blocks = self._allocated_blocks[arena]
|
| 253 |
+
blocks.remove((start, stop))
|
| 254 |
+
if not blocks:
|
| 255 |
+
# Arena is entirely free, discard it from this process
|
| 256 |
+
self._discard_arena(arena)
|
| 257 |
+
|
| 258 |
+
def _free_pending_blocks(self):
|
| 259 |
+
# Free all the blocks in the pending list - called with the lock held.
|
| 260 |
+
while True:
|
| 261 |
+
try:
|
| 262 |
+
block = self._pending_free_blocks.pop()
|
| 263 |
+
except IndexError:
|
| 264 |
+
break
|
| 265 |
+
self._add_free_block(block)
|
| 266 |
+
self._remove_allocated_block(block)
|
| 267 |
+
|
| 268 |
+
def free(self, block):
|
| 269 |
+
# free a block returned by malloc()
|
| 270 |
+
# Since free() can be called asynchronously by the GC, it could happen
|
| 271 |
+
# that it's called while self._lock is held: in that case,
|
| 272 |
+
# self._lock.acquire() would deadlock (issue #12352). To avoid that, a
|
| 273 |
+
# trylock is used instead, and if the lock can't be acquired
|
| 274 |
+
# immediately, the block is added to a list of blocks to be freed
|
| 275 |
+
# synchronously sometimes later from malloc() or free(), by calling
|
| 276 |
+
# _free_pending_blocks() (appending and retrieving from a list is not
|
| 277 |
+
# strictly thread-safe but under CPython it's atomic thanks to the GIL).
|
| 278 |
+
if os.getpid() != self._lastpid:
|
| 279 |
+
raise ValueError(
|
| 280 |
+
"My pid ({0:n}) is not last pid {1:n}".format(
|
| 281 |
+
os.getpid(),self._lastpid))
|
| 282 |
+
if not self._lock.acquire(False):
|
| 283 |
+
# can't acquire the lock right now, add the block to the list of
|
| 284 |
+
# pending blocks to free
|
| 285 |
+
self._pending_free_blocks.append(block)
|
| 286 |
+
else:
|
| 287 |
+
# we hold the lock
|
| 288 |
+
try:
|
| 289 |
+
self._n_frees += 1
|
| 290 |
+
self._free_pending_blocks()
|
| 291 |
+
self._add_free_block(block)
|
| 292 |
+
self._remove_allocated_block(block)
|
| 293 |
+
finally:
|
| 294 |
+
self._lock.release()
|
| 295 |
+
|
| 296 |
+
def malloc(self, size):
|
| 297 |
+
# return a block of right size (possibly rounded up)
|
| 298 |
+
if size < 0:
|
| 299 |
+
raise ValueError("Size {0:n} out of range".format(size))
|
| 300 |
+
if sys.maxsize <= size:
|
| 301 |
+
raise OverflowError("Size {0:n} too large".format(size))
|
| 302 |
+
if os.getpid() != self._lastpid:
|
| 303 |
+
self.__init__() # reinitialize after fork
|
| 304 |
+
with self._lock:
|
| 305 |
+
self._n_mallocs += 1
|
| 306 |
+
# allow pending blocks to be marked available
|
| 307 |
+
self._free_pending_blocks()
|
| 308 |
+
size = self._roundup(max(size, 1), self._alignment)
|
| 309 |
+
(arena, start, stop) = self._malloc(size)
|
| 310 |
+
real_stop = start + size
|
| 311 |
+
if real_stop < stop:
|
| 312 |
+
# if the returned block is larger than necessary, mark
|
| 313 |
+
# the remainder available
|
| 314 |
+
self._add_free_block((arena, real_stop, stop))
|
| 315 |
+
self._allocated_blocks[arena].add((start, real_stop))
|
| 316 |
+
return (arena, start, real_stop)
|
| 317 |
+
|
| 318 |
+
#
|
| 319 |
+
# Class wrapping a block allocated out of a Heap -- can be inherited by child process
|
| 320 |
+
#
|
| 321 |
+
|
| 322 |
+
class BufferWrapper(object):
|
| 323 |
+
|
| 324 |
+
_heap = Heap()
|
| 325 |
+
|
| 326 |
+
def __init__(self, size):
|
| 327 |
+
if size < 0:
|
| 328 |
+
raise ValueError("Size {0:n} out of range".format(size))
|
| 329 |
+
if sys.maxsize <= size:
|
| 330 |
+
raise OverflowError("Size {0:n} too large".format(size))
|
| 331 |
+
block = BufferWrapper._heap.malloc(size)
|
| 332 |
+
self._state = (block, size)
|
| 333 |
+
util.Finalize(self, BufferWrapper._heap.free, args=(block,))
|
| 334 |
+
|
| 335 |
+
def create_memoryview(self):
|
| 336 |
+
(arena, start, stop), size = self._state
|
| 337 |
+
return memoryview(arena.buffer)[start:start+size]
|
miniconda3/envs/ladir/lib/python3.10/multiprocessing/managers.py
ADDED
|
@@ -0,0 +1,1378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Module providing manager classes for dealing
|
| 3 |
+
# with shared objects
|
| 4 |
+
#
|
| 5 |
+
# multiprocessing/managers.py
|
| 6 |
+
#
|
| 7 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 8 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 9 |
+
#
|
| 10 |
+
|
| 11 |
+
__all__ = [ 'BaseManager', 'SyncManager', 'BaseProxy', 'Token' ]
|
| 12 |
+
|
| 13 |
+
#
|
| 14 |
+
# Imports
|
| 15 |
+
#
|
| 16 |
+
|
| 17 |
+
import sys
|
| 18 |
+
import threading
|
| 19 |
+
import signal
|
| 20 |
+
import array
|
| 21 |
+
import queue
|
| 22 |
+
import time
|
| 23 |
+
import types
|
| 24 |
+
import os
|
| 25 |
+
from os import getpid
|
| 26 |
+
|
| 27 |
+
from traceback import format_exc
|
| 28 |
+
|
| 29 |
+
from . import connection
|
| 30 |
+
from .context import reduction, get_spawning_popen, ProcessError
|
| 31 |
+
from . import pool
|
| 32 |
+
from . import process
|
| 33 |
+
from . import util
|
| 34 |
+
from . import get_context
|
| 35 |
+
try:
|
| 36 |
+
from . import shared_memory
|
| 37 |
+
except ImportError:
|
| 38 |
+
HAS_SHMEM = False
|
| 39 |
+
else:
|
| 40 |
+
HAS_SHMEM = True
|
| 41 |
+
__all__.append('SharedMemoryManager')
|
| 42 |
+
|
| 43 |
+
#
|
| 44 |
+
# Register some things for pickling
|
| 45 |
+
#
|
| 46 |
+
|
| 47 |
+
def reduce_array(a):
|
| 48 |
+
return array.array, (a.typecode, a.tobytes())
|
| 49 |
+
reduction.register(array.array, reduce_array)
|
| 50 |
+
|
| 51 |
+
view_types = [type(getattr({}, name)()) for name in ('items','keys','values')]
|
| 52 |
+
if view_types[0] is not list: # only needed in Py3.0
|
| 53 |
+
def rebuild_as_list(obj):
|
| 54 |
+
return list, (list(obj),)
|
| 55 |
+
for view_type in view_types:
|
| 56 |
+
reduction.register(view_type, rebuild_as_list)
|
| 57 |
+
|
| 58 |
+
#
|
| 59 |
+
# Type for identifying shared objects
|
| 60 |
+
#
|
| 61 |
+
|
| 62 |
+
class Token(object):
|
| 63 |
+
'''
|
| 64 |
+
Type to uniquely identify a shared object
|
| 65 |
+
'''
|
| 66 |
+
__slots__ = ('typeid', 'address', 'id')
|
| 67 |
+
|
| 68 |
+
def __init__(self, typeid, address, id):
|
| 69 |
+
(self.typeid, self.address, self.id) = (typeid, address, id)
|
| 70 |
+
|
| 71 |
+
def __getstate__(self):
|
| 72 |
+
return (self.typeid, self.address, self.id)
|
| 73 |
+
|
| 74 |
+
def __setstate__(self, state):
|
| 75 |
+
(self.typeid, self.address, self.id) = state
|
| 76 |
+
|
| 77 |
+
def __repr__(self):
|
| 78 |
+
return '%s(typeid=%r, address=%r, id=%r)' % \
|
| 79 |
+
(self.__class__.__name__, self.typeid, self.address, self.id)
|
| 80 |
+
|
| 81 |
+
#
|
| 82 |
+
# Function for communication with a manager's server process
|
| 83 |
+
#
|
| 84 |
+
|
| 85 |
+
def dispatch(c, id, methodname, args=(), kwds={}):
|
| 86 |
+
'''
|
| 87 |
+
Send a message to manager using connection `c` and return response
|
| 88 |
+
'''
|
| 89 |
+
c.send((id, methodname, args, kwds))
|
| 90 |
+
kind, result = c.recv()
|
| 91 |
+
if kind == '#RETURN':
|
| 92 |
+
return result
|
| 93 |
+
raise convert_to_error(kind, result)
|
| 94 |
+
|
| 95 |
+
def convert_to_error(kind, result):
|
| 96 |
+
if kind == '#ERROR':
|
| 97 |
+
return result
|
| 98 |
+
elif kind in ('#TRACEBACK', '#UNSERIALIZABLE'):
|
| 99 |
+
if not isinstance(result, str):
|
| 100 |
+
raise TypeError(
|
| 101 |
+
"Result {0!r} (kind '{1}') type is {2}, not str".format(
|
| 102 |
+
result, kind, type(result)))
|
| 103 |
+
if kind == '#UNSERIALIZABLE':
|
| 104 |
+
return RemoteError('Unserializable message: %s\n' % result)
|
| 105 |
+
else:
|
| 106 |
+
return RemoteError(result)
|
| 107 |
+
else:
|
| 108 |
+
return ValueError('Unrecognized message type {!r}'.format(kind))
|
| 109 |
+
|
| 110 |
+
class RemoteError(Exception):
|
| 111 |
+
def __str__(self):
|
| 112 |
+
return ('\n' + '-'*75 + '\n' + str(self.args[0]) + '-'*75)
|
| 113 |
+
|
| 114 |
+
#
|
| 115 |
+
# Functions for finding the method names of an object
|
| 116 |
+
#
|
| 117 |
+
|
| 118 |
+
def all_methods(obj):
|
| 119 |
+
'''
|
| 120 |
+
Return a list of names of methods of `obj`
|
| 121 |
+
'''
|
| 122 |
+
temp = []
|
| 123 |
+
for name in dir(obj):
|
| 124 |
+
func = getattr(obj, name)
|
| 125 |
+
if callable(func):
|
| 126 |
+
temp.append(name)
|
| 127 |
+
return temp
|
| 128 |
+
|
| 129 |
+
def public_methods(obj):
|
| 130 |
+
'''
|
| 131 |
+
Return a list of names of methods of `obj` which do not start with '_'
|
| 132 |
+
'''
|
| 133 |
+
return [name for name in all_methods(obj) if name[0] != '_']
|
| 134 |
+
|
| 135 |
+
#
|
| 136 |
+
# Server which is run in a process controlled by a manager
|
| 137 |
+
#
|
| 138 |
+
|
| 139 |
+
class Server(object):
|
| 140 |
+
'''
|
| 141 |
+
Server class which runs in a process controlled by a manager object
|
| 142 |
+
'''
|
| 143 |
+
public = ['shutdown', 'create', 'accept_connection', 'get_methods',
|
| 144 |
+
'debug_info', 'number_of_objects', 'dummy', 'incref', 'decref']
|
| 145 |
+
|
| 146 |
+
def __init__(self, registry, address, authkey, serializer):
|
| 147 |
+
if not isinstance(authkey, bytes):
|
| 148 |
+
raise TypeError(
|
| 149 |
+
"Authkey {0!r} is type {1!s}, not bytes".format(
|
| 150 |
+
authkey, type(authkey)))
|
| 151 |
+
self.registry = registry
|
| 152 |
+
self.authkey = process.AuthenticationString(authkey)
|
| 153 |
+
Listener, Client = listener_client[serializer]
|
| 154 |
+
|
| 155 |
+
# do authentication later
|
| 156 |
+
self.listener = Listener(address=address, backlog=16)
|
| 157 |
+
self.address = self.listener.address
|
| 158 |
+
|
| 159 |
+
self.id_to_obj = {'0': (None, ())}
|
| 160 |
+
self.id_to_refcount = {}
|
| 161 |
+
self.id_to_local_proxy_obj = {}
|
| 162 |
+
self.mutex = threading.Lock()
|
| 163 |
+
|
| 164 |
+
def serve_forever(self):
|
| 165 |
+
'''
|
| 166 |
+
Run the server forever
|
| 167 |
+
'''
|
| 168 |
+
self.stop_event = threading.Event()
|
| 169 |
+
process.current_process()._manager_server = self
|
| 170 |
+
try:
|
| 171 |
+
accepter = threading.Thread(target=self.accepter)
|
| 172 |
+
accepter.daemon = True
|
| 173 |
+
accepter.start()
|
| 174 |
+
try:
|
| 175 |
+
while not self.stop_event.is_set():
|
| 176 |
+
self.stop_event.wait(1)
|
| 177 |
+
except (KeyboardInterrupt, SystemExit):
|
| 178 |
+
pass
|
| 179 |
+
finally:
|
| 180 |
+
if sys.stdout != sys.__stdout__: # what about stderr?
|
| 181 |
+
util.debug('resetting stdout, stderr')
|
| 182 |
+
sys.stdout = sys.__stdout__
|
| 183 |
+
sys.stderr = sys.__stderr__
|
| 184 |
+
sys.exit(0)
|
| 185 |
+
|
| 186 |
+
def accepter(self):
|
| 187 |
+
while True:
|
| 188 |
+
try:
|
| 189 |
+
c = self.listener.accept()
|
| 190 |
+
except OSError:
|
| 191 |
+
continue
|
| 192 |
+
t = threading.Thread(target=self.handle_request, args=(c,))
|
| 193 |
+
t.daemon = True
|
| 194 |
+
t.start()
|
| 195 |
+
|
| 196 |
+
def _handle_request(self, c):
|
| 197 |
+
request = None
|
| 198 |
+
try:
|
| 199 |
+
connection.deliver_challenge(c, self.authkey)
|
| 200 |
+
connection.answer_challenge(c, self.authkey)
|
| 201 |
+
request = c.recv()
|
| 202 |
+
ignore, funcname, args, kwds = request
|
| 203 |
+
assert funcname in self.public, '%r unrecognized' % funcname
|
| 204 |
+
func = getattr(self, funcname)
|
| 205 |
+
except Exception:
|
| 206 |
+
msg = ('#TRACEBACK', format_exc())
|
| 207 |
+
else:
|
| 208 |
+
try:
|
| 209 |
+
result = func(c, *args, **kwds)
|
| 210 |
+
except Exception:
|
| 211 |
+
msg = ('#TRACEBACK', format_exc())
|
| 212 |
+
else:
|
| 213 |
+
msg = ('#RETURN', result)
|
| 214 |
+
|
| 215 |
+
try:
|
| 216 |
+
c.send(msg)
|
| 217 |
+
except Exception as e:
|
| 218 |
+
try:
|
| 219 |
+
c.send(('#TRACEBACK', format_exc()))
|
| 220 |
+
except Exception:
|
| 221 |
+
pass
|
| 222 |
+
util.info('Failure to send message: %r', msg)
|
| 223 |
+
util.info(' ... request was %r', request)
|
| 224 |
+
util.info(' ... exception was %r', e)
|
| 225 |
+
|
| 226 |
+
def handle_request(self, conn):
|
| 227 |
+
'''
|
| 228 |
+
Handle a new connection
|
| 229 |
+
'''
|
| 230 |
+
try:
|
| 231 |
+
self._handle_request(conn)
|
| 232 |
+
except SystemExit:
|
| 233 |
+
# Server.serve_client() calls sys.exit(0) on EOF
|
| 234 |
+
pass
|
| 235 |
+
finally:
|
| 236 |
+
conn.close()
|
| 237 |
+
|
| 238 |
+
def serve_client(self, conn):
|
| 239 |
+
'''
|
| 240 |
+
Handle requests from the proxies in a particular process/thread
|
| 241 |
+
'''
|
| 242 |
+
util.debug('starting server thread to service %r',
|
| 243 |
+
threading.current_thread().name)
|
| 244 |
+
|
| 245 |
+
recv = conn.recv
|
| 246 |
+
send = conn.send
|
| 247 |
+
id_to_obj = self.id_to_obj
|
| 248 |
+
|
| 249 |
+
while not self.stop_event.is_set():
|
| 250 |
+
|
| 251 |
+
try:
|
| 252 |
+
methodname = obj = None
|
| 253 |
+
request = recv()
|
| 254 |
+
ident, methodname, args, kwds = request
|
| 255 |
+
try:
|
| 256 |
+
obj, exposed, gettypeid = id_to_obj[ident]
|
| 257 |
+
except KeyError as ke:
|
| 258 |
+
try:
|
| 259 |
+
obj, exposed, gettypeid = \
|
| 260 |
+
self.id_to_local_proxy_obj[ident]
|
| 261 |
+
except KeyError:
|
| 262 |
+
raise ke
|
| 263 |
+
|
| 264 |
+
if methodname not in exposed:
|
| 265 |
+
raise AttributeError(
|
| 266 |
+
'method %r of %r object is not in exposed=%r' %
|
| 267 |
+
(methodname, type(obj), exposed)
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
function = getattr(obj, methodname)
|
| 271 |
+
|
| 272 |
+
try:
|
| 273 |
+
res = function(*args, **kwds)
|
| 274 |
+
except Exception as e:
|
| 275 |
+
msg = ('#ERROR', e)
|
| 276 |
+
else:
|
| 277 |
+
typeid = gettypeid and gettypeid.get(methodname, None)
|
| 278 |
+
if typeid:
|
| 279 |
+
rident, rexposed = self.create(conn, typeid, res)
|
| 280 |
+
token = Token(typeid, self.address, rident)
|
| 281 |
+
msg = ('#PROXY', (rexposed, token))
|
| 282 |
+
else:
|
| 283 |
+
msg = ('#RETURN', res)
|
| 284 |
+
|
| 285 |
+
except AttributeError:
|
| 286 |
+
if methodname is None:
|
| 287 |
+
msg = ('#TRACEBACK', format_exc())
|
| 288 |
+
else:
|
| 289 |
+
try:
|
| 290 |
+
fallback_func = self.fallback_mapping[methodname]
|
| 291 |
+
result = fallback_func(
|
| 292 |
+
self, conn, ident, obj, *args, **kwds
|
| 293 |
+
)
|
| 294 |
+
msg = ('#RETURN', result)
|
| 295 |
+
except Exception:
|
| 296 |
+
msg = ('#TRACEBACK', format_exc())
|
| 297 |
+
|
| 298 |
+
except EOFError:
|
| 299 |
+
util.debug('got EOF -- exiting thread serving %r',
|
| 300 |
+
threading.current_thread().name)
|
| 301 |
+
sys.exit(0)
|
| 302 |
+
|
| 303 |
+
except Exception:
|
| 304 |
+
msg = ('#TRACEBACK', format_exc())
|
| 305 |
+
|
| 306 |
+
try:
|
| 307 |
+
try:
|
| 308 |
+
send(msg)
|
| 309 |
+
except Exception:
|
| 310 |
+
send(('#UNSERIALIZABLE', format_exc()))
|
| 311 |
+
except Exception as e:
|
| 312 |
+
util.info('exception in thread serving %r',
|
| 313 |
+
threading.current_thread().name)
|
| 314 |
+
util.info(' ... message was %r', msg)
|
| 315 |
+
util.info(' ... exception was %r', e)
|
| 316 |
+
conn.close()
|
| 317 |
+
sys.exit(1)
|
| 318 |
+
|
| 319 |
+
def fallback_getvalue(self, conn, ident, obj):
|
| 320 |
+
return obj
|
| 321 |
+
|
| 322 |
+
def fallback_str(self, conn, ident, obj):
|
| 323 |
+
return str(obj)
|
| 324 |
+
|
| 325 |
+
def fallback_repr(self, conn, ident, obj):
|
| 326 |
+
return repr(obj)
|
| 327 |
+
|
| 328 |
+
fallback_mapping = {
|
| 329 |
+
'__str__':fallback_str,
|
| 330 |
+
'__repr__':fallback_repr,
|
| 331 |
+
'#GETVALUE':fallback_getvalue
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
def dummy(self, c):
|
| 335 |
+
pass
|
| 336 |
+
|
| 337 |
+
def debug_info(self, c):
|
| 338 |
+
'''
|
| 339 |
+
Return some info --- useful to spot problems with refcounting
|
| 340 |
+
'''
|
| 341 |
+
# Perhaps include debug info about 'c'?
|
| 342 |
+
with self.mutex:
|
| 343 |
+
result = []
|
| 344 |
+
keys = list(self.id_to_refcount.keys())
|
| 345 |
+
keys.sort()
|
| 346 |
+
for ident in keys:
|
| 347 |
+
if ident != '0':
|
| 348 |
+
result.append(' %s: refcount=%s\n %s' %
|
| 349 |
+
(ident, self.id_to_refcount[ident],
|
| 350 |
+
str(self.id_to_obj[ident][0])[:75]))
|
| 351 |
+
return '\n'.join(result)
|
| 352 |
+
|
| 353 |
+
def number_of_objects(self, c):
|
| 354 |
+
'''
|
| 355 |
+
Number of shared objects
|
| 356 |
+
'''
|
| 357 |
+
# Doesn't use (len(self.id_to_obj) - 1) as we shouldn't count ident='0'
|
| 358 |
+
return len(self.id_to_refcount)
|
| 359 |
+
|
| 360 |
+
def shutdown(self, c):
|
| 361 |
+
'''
|
| 362 |
+
Shutdown this process
|
| 363 |
+
'''
|
| 364 |
+
try:
|
| 365 |
+
util.debug('manager received shutdown message')
|
| 366 |
+
c.send(('#RETURN', None))
|
| 367 |
+
except:
|
| 368 |
+
import traceback
|
| 369 |
+
traceback.print_exc()
|
| 370 |
+
finally:
|
| 371 |
+
self.stop_event.set()
|
| 372 |
+
|
| 373 |
+
def create(self, c, typeid, /, *args, **kwds):
|
| 374 |
+
'''
|
| 375 |
+
Create a new shared object and return its id
|
| 376 |
+
'''
|
| 377 |
+
with self.mutex:
|
| 378 |
+
callable, exposed, method_to_typeid, proxytype = \
|
| 379 |
+
self.registry[typeid]
|
| 380 |
+
|
| 381 |
+
if callable is None:
|
| 382 |
+
if kwds or (len(args) != 1):
|
| 383 |
+
raise ValueError(
|
| 384 |
+
"Without callable, must have one non-keyword argument")
|
| 385 |
+
obj = args[0]
|
| 386 |
+
else:
|
| 387 |
+
obj = callable(*args, **kwds)
|
| 388 |
+
|
| 389 |
+
if exposed is None:
|
| 390 |
+
exposed = public_methods(obj)
|
| 391 |
+
if method_to_typeid is not None:
|
| 392 |
+
if not isinstance(method_to_typeid, dict):
|
| 393 |
+
raise TypeError(
|
| 394 |
+
"Method_to_typeid {0!r}: type {1!s}, not dict".format(
|
| 395 |
+
method_to_typeid, type(method_to_typeid)))
|
| 396 |
+
exposed = list(exposed) + list(method_to_typeid)
|
| 397 |
+
|
| 398 |
+
ident = '%x' % id(obj) # convert to string because xmlrpclib
|
| 399 |
+
# only has 32 bit signed integers
|
| 400 |
+
util.debug('%r callable returned object with id %r', typeid, ident)
|
| 401 |
+
|
| 402 |
+
self.id_to_obj[ident] = (obj, set(exposed), method_to_typeid)
|
| 403 |
+
if ident not in self.id_to_refcount:
|
| 404 |
+
self.id_to_refcount[ident] = 0
|
| 405 |
+
|
| 406 |
+
self.incref(c, ident)
|
| 407 |
+
return ident, tuple(exposed)
|
| 408 |
+
|
| 409 |
+
def get_methods(self, c, token):
|
| 410 |
+
'''
|
| 411 |
+
Return the methods of the shared object indicated by token
|
| 412 |
+
'''
|
| 413 |
+
return tuple(self.id_to_obj[token.id][1])
|
| 414 |
+
|
| 415 |
+
def accept_connection(self, c, name):
|
| 416 |
+
'''
|
| 417 |
+
Spawn a new thread to serve this connection
|
| 418 |
+
'''
|
| 419 |
+
threading.current_thread().name = name
|
| 420 |
+
c.send(('#RETURN', None))
|
| 421 |
+
self.serve_client(c)
|
| 422 |
+
|
| 423 |
+
def incref(self, c, ident):
|
| 424 |
+
with self.mutex:
|
| 425 |
+
try:
|
| 426 |
+
self.id_to_refcount[ident] += 1
|
| 427 |
+
except KeyError as ke:
|
| 428 |
+
# If no external references exist but an internal (to the
|
| 429 |
+
# manager) still does and a new external reference is created
|
| 430 |
+
# from it, restore the manager's tracking of it from the
|
| 431 |
+
# previously stashed internal ref.
|
| 432 |
+
if ident in self.id_to_local_proxy_obj:
|
| 433 |
+
self.id_to_refcount[ident] = 1
|
| 434 |
+
self.id_to_obj[ident] = \
|
| 435 |
+
self.id_to_local_proxy_obj[ident]
|
| 436 |
+
obj, exposed, gettypeid = self.id_to_obj[ident]
|
| 437 |
+
util.debug('Server re-enabled tracking & INCREF %r', ident)
|
| 438 |
+
else:
|
| 439 |
+
raise ke
|
| 440 |
+
|
| 441 |
+
def decref(self, c, ident):
|
| 442 |
+
if ident not in self.id_to_refcount and \
|
| 443 |
+
ident in self.id_to_local_proxy_obj:
|
| 444 |
+
util.debug('Server DECREF skipping %r', ident)
|
| 445 |
+
return
|
| 446 |
+
|
| 447 |
+
with self.mutex:
|
| 448 |
+
if self.id_to_refcount[ident] <= 0:
|
| 449 |
+
raise AssertionError(
|
| 450 |
+
"Id {0!s} ({1!r}) has refcount {2:n}, not 1+".format(
|
| 451 |
+
ident, self.id_to_obj[ident],
|
| 452 |
+
self.id_to_refcount[ident]))
|
| 453 |
+
self.id_to_refcount[ident] -= 1
|
| 454 |
+
if self.id_to_refcount[ident] == 0:
|
| 455 |
+
del self.id_to_refcount[ident]
|
| 456 |
+
|
| 457 |
+
if ident not in self.id_to_refcount:
|
| 458 |
+
# Two-step process in case the object turns out to contain other
|
| 459 |
+
# proxy objects (e.g. a managed list of managed lists).
|
| 460 |
+
# Otherwise, deleting self.id_to_obj[ident] would trigger the
|
| 461 |
+
# deleting of the stored value (another managed object) which would
|
| 462 |
+
# in turn attempt to acquire the mutex that is already held here.
|
| 463 |
+
self.id_to_obj[ident] = (None, (), None) # thread-safe
|
| 464 |
+
util.debug('disposing of obj with id %r', ident)
|
| 465 |
+
with self.mutex:
|
| 466 |
+
del self.id_to_obj[ident]
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
#
|
| 470 |
+
# Class to represent state of a manager
|
| 471 |
+
#
|
| 472 |
+
|
| 473 |
+
class State(object):
|
| 474 |
+
__slots__ = ['value']
|
| 475 |
+
INITIAL = 0
|
| 476 |
+
STARTED = 1
|
| 477 |
+
SHUTDOWN = 2
|
| 478 |
+
|
| 479 |
+
#
|
| 480 |
+
# Mapping from serializer name to Listener and Client types
|
| 481 |
+
#
|
| 482 |
+
|
| 483 |
+
listener_client = {
|
| 484 |
+
'pickle' : (connection.Listener, connection.Client),
|
| 485 |
+
'xmlrpclib' : (connection.XmlListener, connection.XmlClient)
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
#
|
| 489 |
+
# Definition of BaseManager
|
| 490 |
+
#
|
| 491 |
+
|
| 492 |
+
class BaseManager(object):
|
| 493 |
+
'''
|
| 494 |
+
Base class for managers
|
| 495 |
+
'''
|
| 496 |
+
_registry = {}
|
| 497 |
+
_Server = Server
|
| 498 |
+
|
| 499 |
+
def __init__(self, address=None, authkey=None, serializer='pickle',
|
| 500 |
+
ctx=None):
|
| 501 |
+
if authkey is None:
|
| 502 |
+
authkey = process.current_process().authkey
|
| 503 |
+
self._address = address # XXX not final address if eg ('', 0)
|
| 504 |
+
self._authkey = process.AuthenticationString(authkey)
|
| 505 |
+
self._state = State()
|
| 506 |
+
self._state.value = State.INITIAL
|
| 507 |
+
self._serializer = serializer
|
| 508 |
+
self._Listener, self._Client = listener_client[serializer]
|
| 509 |
+
self._ctx = ctx or get_context()
|
| 510 |
+
|
| 511 |
+
def get_server(self):
|
| 512 |
+
'''
|
| 513 |
+
Return server object with serve_forever() method and address attribute
|
| 514 |
+
'''
|
| 515 |
+
if self._state.value != State.INITIAL:
|
| 516 |
+
if self._state.value == State.STARTED:
|
| 517 |
+
raise ProcessError("Already started server")
|
| 518 |
+
elif self._state.value == State.SHUTDOWN:
|
| 519 |
+
raise ProcessError("Manager has shut down")
|
| 520 |
+
else:
|
| 521 |
+
raise ProcessError(
|
| 522 |
+
"Unknown state {!r}".format(self._state.value))
|
| 523 |
+
return Server(self._registry, self._address,
|
| 524 |
+
self._authkey, self._serializer)
|
| 525 |
+
|
| 526 |
+
def connect(self):
|
| 527 |
+
'''
|
| 528 |
+
Connect manager object to the server process
|
| 529 |
+
'''
|
| 530 |
+
Listener, Client = listener_client[self._serializer]
|
| 531 |
+
conn = Client(self._address, authkey=self._authkey)
|
| 532 |
+
dispatch(conn, None, 'dummy')
|
| 533 |
+
self._state.value = State.STARTED
|
| 534 |
+
|
| 535 |
+
def start(self, initializer=None, initargs=()):
|
| 536 |
+
'''
|
| 537 |
+
Spawn a server process for this manager object
|
| 538 |
+
'''
|
| 539 |
+
if self._state.value != State.INITIAL:
|
| 540 |
+
if self._state.value == State.STARTED:
|
| 541 |
+
raise ProcessError("Already started server")
|
| 542 |
+
elif self._state.value == State.SHUTDOWN:
|
| 543 |
+
raise ProcessError("Manager has shut down")
|
| 544 |
+
else:
|
| 545 |
+
raise ProcessError(
|
| 546 |
+
"Unknown state {!r}".format(self._state.value))
|
| 547 |
+
|
| 548 |
+
if initializer is not None and not callable(initializer):
|
| 549 |
+
raise TypeError('initializer must be a callable')
|
| 550 |
+
|
| 551 |
+
# pipe over which we will retrieve address of server
|
| 552 |
+
reader, writer = connection.Pipe(duplex=False)
|
| 553 |
+
|
| 554 |
+
# spawn process which runs a server
|
| 555 |
+
self._process = self._ctx.Process(
|
| 556 |
+
target=type(self)._run_server,
|
| 557 |
+
args=(self._registry, self._address, self._authkey,
|
| 558 |
+
self._serializer, writer, initializer, initargs),
|
| 559 |
+
)
|
| 560 |
+
ident = ':'.join(str(i) for i in self._process._identity)
|
| 561 |
+
self._process.name = type(self).__name__ + '-' + ident
|
| 562 |
+
self._process.start()
|
| 563 |
+
|
| 564 |
+
# get address of server
|
| 565 |
+
writer.close()
|
| 566 |
+
self._address = reader.recv()
|
| 567 |
+
reader.close()
|
| 568 |
+
|
| 569 |
+
# register a finalizer
|
| 570 |
+
self._state.value = State.STARTED
|
| 571 |
+
self.shutdown = util.Finalize(
|
| 572 |
+
self, type(self)._finalize_manager,
|
| 573 |
+
args=(self._process, self._address, self._authkey,
|
| 574 |
+
self._state, self._Client),
|
| 575 |
+
exitpriority=0
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
@classmethod
|
| 579 |
+
def _run_server(cls, registry, address, authkey, serializer, writer,
|
| 580 |
+
initializer=None, initargs=()):
|
| 581 |
+
'''
|
| 582 |
+
Create a server, report its address and run it
|
| 583 |
+
'''
|
| 584 |
+
# bpo-36368: protect server process from KeyboardInterrupt signals
|
| 585 |
+
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
| 586 |
+
|
| 587 |
+
if initializer is not None:
|
| 588 |
+
initializer(*initargs)
|
| 589 |
+
|
| 590 |
+
# create server
|
| 591 |
+
server = cls._Server(registry, address, authkey, serializer)
|
| 592 |
+
|
| 593 |
+
# inform parent process of the server's address
|
| 594 |
+
writer.send(server.address)
|
| 595 |
+
writer.close()
|
| 596 |
+
|
| 597 |
+
# run the manager
|
| 598 |
+
util.info('manager serving at %r', server.address)
|
| 599 |
+
server.serve_forever()
|
| 600 |
+
|
| 601 |
+
def _create(self, typeid, /, *args, **kwds):
|
| 602 |
+
'''
|
| 603 |
+
Create a new shared object; return the token and exposed tuple
|
| 604 |
+
'''
|
| 605 |
+
assert self._state.value == State.STARTED, 'server not yet started'
|
| 606 |
+
conn = self._Client(self._address, authkey=self._authkey)
|
| 607 |
+
try:
|
| 608 |
+
id, exposed = dispatch(conn, None, 'create', (typeid,)+args, kwds)
|
| 609 |
+
finally:
|
| 610 |
+
conn.close()
|
| 611 |
+
return Token(typeid, self._address, id), exposed
|
| 612 |
+
|
| 613 |
+
def join(self, timeout=None):
|
| 614 |
+
'''
|
| 615 |
+
Join the manager process (if it has been spawned)
|
| 616 |
+
'''
|
| 617 |
+
if self._process is not None:
|
| 618 |
+
self._process.join(timeout)
|
| 619 |
+
if not self._process.is_alive():
|
| 620 |
+
self._process = None
|
| 621 |
+
|
| 622 |
+
def _debug_info(self):
|
| 623 |
+
'''
|
| 624 |
+
Return some info about the servers shared objects and connections
|
| 625 |
+
'''
|
| 626 |
+
conn = self._Client(self._address, authkey=self._authkey)
|
| 627 |
+
try:
|
| 628 |
+
return dispatch(conn, None, 'debug_info')
|
| 629 |
+
finally:
|
| 630 |
+
conn.close()
|
| 631 |
+
|
| 632 |
+
def _number_of_objects(self):
|
| 633 |
+
'''
|
| 634 |
+
Return the number of shared objects
|
| 635 |
+
'''
|
| 636 |
+
conn = self._Client(self._address, authkey=self._authkey)
|
| 637 |
+
try:
|
| 638 |
+
return dispatch(conn, None, 'number_of_objects')
|
| 639 |
+
finally:
|
| 640 |
+
conn.close()
|
| 641 |
+
|
| 642 |
+
def __enter__(self):
|
| 643 |
+
if self._state.value == State.INITIAL:
|
| 644 |
+
self.start()
|
| 645 |
+
if self._state.value != State.STARTED:
|
| 646 |
+
if self._state.value == State.INITIAL:
|
| 647 |
+
raise ProcessError("Unable to start server")
|
| 648 |
+
elif self._state.value == State.SHUTDOWN:
|
| 649 |
+
raise ProcessError("Manager has shut down")
|
| 650 |
+
else:
|
| 651 |
+
raise ProcessError(
|
| 652 |
+
"Unknown state {!r}".format(self._state.value))
|
| 653 |
+
return self
|
| 654 |
+
|
| 655 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 656 |
+
self.shutdown()
|
| 657 |
+
|
| 658 |
+
@staticmethod
|
| 659 |
+
def _finalize_manager(process, address, authkey, state, _Client):
|
| 660 |
+
'''
|
| 661 |
+
Shutdown the manager process; will be registered as a finalizer
|
| 662 |
+
'''
|
| 663 |
+
if process.is_alive():
|
| 664 |
+
util.info('sending shutdown message to manager')
|
| 665 |
+
try:
|
| 666 |
+
conn = _Client(address, authkey=authkey)
|
| 667 |
+
try:
|
| 668 |
+
dispatch(conn, None, 'shutdown')
|
| 669 |
+
finally:
|
| 670 |
+
conn.close()
|
| 671 |
+
except Exception:
|
| 672 |
+
pass
|
| 673 |
+
|
| 674 |
+
process.join(timeout=1.0)
|
| 675 |
+
if process.is_alive():
|
| 676 |
+
util.info('manager still alive')
|
| 677 |
+
if hasattr(process, 'terminate'):
|
| 678 |
+
util.info('trying to `terminate()` manager process')
|
| 679 |
+
process.terminate()
|
| 680 |
+
process.join(timeout=1.0)
|
| 681 |
+
if process.is_alive():
|
| 682 |
+
util.info('manager still alive after terminate')
|
| 683 |
+
|
| 684 |
+
state.value = State.SHUTDOWN
|
| 685 |
+
try:
|
| 686 |
+
del BaseProxy._address_to_local[address]
|
| 687 |
+
except KeyError:
|
| 688 |
+
pass
|
| 689 |
+
|
| 690 |
+
@property
|
| 691 |
+
def address(self):
|
| 692 |
+
return self._address
|
| 693 |
+
|
| 694 |
+
@classmethod
|
| 695 |
+
def register(cls, typeid, callable=None, proxytype=None, exposed=None,
|
| 696 |
+
method_to_typeid=None, create_method=True):
|
| 697 |
+
'''
|
| 698 |
+
Register a typeid with the manager type
|
| 699 |
+
'''
|
| 700 |
+
if '_registry' not in cls.__dict__:
|
| 701 |
+
cls._registry = cls._registry.copy()
|
| 702 |
+
|
| 703 |
+
if proxytype is None:
|
| 704 |
+
proxytype = AutoProxy
|
| 705 |
+
|
| 706 |
+
exposed = exposed or getattr(proxytype, '_exposed_', None)
|
| 707 |
+
|
| 708 |
+
method_to_typeid = method_to_typeid or \
|
| 709 |
+
getattr(proxytype, '_method_to_typeid_', None)
|
| 710 |
+
|
| 711 |
+
if method_to_typeid:
|
| 712 |
+
for key, value in list(method_to_typeid.items()): # isinstance?
|
| 713 |
+
assert type(key) is str, '%r is not a string' % key
|
| 714 |
+
assert type(value) is str, '%r is not a string' % value
|
| 715 |
+
|
| 716 |
+
cls._registry[typeid] = (
|
| 717 |
+
callable, exposed, method_to_typeid, proxytype
|
| 718 |
+
)
|
| 719 |
+
|
| 720 |
+
if create_method:
|
| 721 |
+
def temp(self, /, *args, **kwds):
|
| 722 |
+
util.debug('requesting creation of a shared %r object', typeid)
|
| 723 |
+
token, exp = self._create(typeid, *args, **kwds)
|
| 724 |
+
proxy = proxytype(
|
| 725 |
+
token, self._serializer, manager=self,
|
| 726 |
+
authkey=self._authkey, exposed=exp
|
| 727 |
+
)
|
| 728 |
+
conn = self._Client(token.address, authkey=self._authkey)
|
| 729 |
+
dispatch(conn, None, 'decref', (token.id,))
|
| 730 |
+
return proxy
|
| 731 |
+
temp.__name__ = typeid
|
| 732 |
+
setattr(cls, typeid, temp)
|
| 733 |
+
|
| 734 |
+
#
|
| 735 |
+
# Subclass of set which get cleared after a fork
|
| 736 |
+
#
|
| 737 |
+
|
| 738 |
+
class ProcessLocalSet(set):
|
| 739 |
+
def __init__(self):
|
| 740 |
+
util.register_after_fork(self, lambda obj: obj.clear())
|
| 741 |
+
def __reduce__(self):
|
| 742 |
+
return type(self), ()
|
| 743 |
+
|
| 744 |
+
#
|
| 745 |
+
# Definition of BaseProxy
|
| 746 |
+
#
|
| 747 |
+
|
| 748 |
+
class BaseProxy(object):
|
| 749 |
+
'''
|
| 750 |
+
A base for proxies of shared objects
|
| 751 |
+
'''
|
| 752 |
+
_address_to_local = {}
|
| 753 |
+
_mutex = util.ForkAwareThreadLock()
|
| 754 |
+
|
| 755 |
+
def __init__(self, token, serializer, manager=None,
|
| 756 |
+
authkey=None, exposed=None, incref=True, manager_owned=False):
|
| 757 |
+
with BaseProxy._mutex:
|
| 758 |
+
tls_idset = BaseProxy._address_to_local.get(token.address, None)
|
| 759 |
+
if tls_idset is None:
|
| 760 |
+
tls_idset = util.ForkAwareLocal(), ProcessLocalSet()
|
| 761 |
+
BaseProxy._address_to_local[token.address] = tls_idset
|
| 762 |
+
|
| 763 |
+
# self._tls is used to record the connection used by this
|
| 764 |
+
# thread to communicate with the manager at token.address
|
| 765 |
+
self._tls = tls_idset[0]
|
| 766 |
+
|
| 767 |
+
# self._idset is used to record the identities of all shared
|
| 768 |
+
# objects for which the current process owns references and
|
| 769 |
+
# which are in the manager at token.address
|
| 770 |
+
self._idset = tls_idset[1]
|
| 771 |
+
|
| 772 |
+
self._token = token
|
| 773 |
+
self._id = self._token.id
|
| 774 |
+
self._manager = manager
|
| 775 |
+
self._serializer = serializer
|
| 776 |
+
self._Client = listener_client[serializer][1]
|
| 777 |
+
|
| 778 |
+
# Should be set to True only when a proxy object is being created
|
| 779 |
+
# on the manager server; primary use case: nested proxy objects.
|
| 780 |
+
# RebuildProxy detects when a proxy is being created on the manager
|
| 781 |
+
# and sets this value appropriately.
|
| 782 |
+
self._owned_by_manager = manager_owned
|
| 783 |
+
|
| 784 |
+
if authkey is not None:
|
| 785 |
+
self._authkey = process.AuthenticationString(authkey)
|
| 786 |
+
elif self._manager is not None:
|
| 787 |
+
self._authkey = self._manager._authkey
|
| 788 |
+
else:
|
| 789 |
+
self._authkey = process.current_process().authkey
|
| 790 |
+
|
| 791 |
+
if incref:
|
| 792 |
+
self._incref()
|
| 793 |
+
|
| 794 |
+
util.register_after_fork(self, BaseProxy._after_fork)
|
| 795 |
+
|
| 796 |
+
def _connect(self):
|
| 797 |
+
util.debug('making connection to manager')
|
| 798 |
+
name = process.current_process().name
|
| 799 |
+
if threading.current_thread().name != 'MainThread':
|
| 800 |
+
name += '|' + threading.current_thread().name
|
| 801 |
+
conn = self._Client(self._token.address, authkey=self._authkey)
|
| 802 |
+
dispatch(conn, None, 'accept_connection', (name,))
|
| 803 |
+
self._tls.connection = conn
|
| 804 |
+
|
| 805 |
+
def _callmethod(self, methodname, args=(), kwds={}):
|
| 806 |
+
'''
|
| 807 |
+
Try to call a method of the referent and return a copy of the result
|
| 808 |
+
'''
|
| 809 |
+
try:
|
| 810 |
+
conn = self._tls.connection
|
| 811 |
+
except AttributeError:
|
| 812 |
+
util.debug('thread %r does not own a connection',
|
| 813 |
+
threading.current_thread().name)
|
| 814 |
+
self._connect()
|
| 815 |
+
conn = self._tls.connection
|
| 816 |
+
|
| 817 |
+
conn.send((self._id, methodname, args, kwds))
|
| 818 |
+
kind, result = conn.recv()
|
| 819 |
+
|
| 820 |
+
if kind == '#RETURN':
|
| 821 |
+
return result
|
| 822 |
+
elif kind == '#PROXY':
|
| 823 |
+
exposed, token = result
|
| 824 |
+
proxytype = self._manager._registry[token.typeid][-1]
|
| 825 |
+
token.address = self._token.address
|
| 826 |
+
proxy = proxytype(
|
| 827 |
+
token, self._serializer, manager=self._manager,
|
| 828 |
+
authkey=self._authkey, exposed=exposed
|
| 829 |
+
)
|
| 830 |
+
conn = self._Client(token.address, authkey=self._authkey)
|
| 831 |
+
dispatch(conn, None, 'decref', (token.id,))
|
| 832 |
+
return proxy
|
| 833 |
+
raise convert_to_error(kind, result)
|
| 834 |
+
|
| 835 |
+
def _getvalue(self):
|
| 836 |
+
'''
|
| 837 |
+
Get a copy of the value of the referent
|
| 838 |
+
'''
|
| 839 |
+
return self._callmethod('#GETVALUE')
|
| 840 |
+
|
| 841 |
+
def _incref(self):
|
| 842 |
+
if self._owned_by_manager:
|
| 843 |
+
util.debug('owned_by_manager skipped INCREF of %r', self._token.id)
|
| 844 |
+
return
|
| 845 |
+
|
| 846 |
+
conn = self._Client(self._token.address, authkey=self._authkey)
|
| 847 |
+
dispatch(conn, None, 'incref', (self._id,))
|
| 848 |
+
util.debug('INCREF %r', self._token.id)
|
| 849 |
+
|
| 850 |
+
self._idset.add(self._id)
|
| 851 |
+
|
| 852 |
+
state = self._manager and self._manager._state
|
| 853 |
+
|
| 854 |
+
self._close = util.Finalize(
|
| 855 |
+
self, BaseProxy._decref,
|
| 856 |
+
args=(self._token, self._authkey, state,
|
| 857 |
+
self._tls, self._idset, self._Client),
|
| 858 |
+
exitpriority=10
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
@staticmethod
|
| 862 |
+
def _decref(token, authkey, state, tls, idset, _Client):
|
| 863 |
+
idset.discard(token.id)
|
| 864 |
+
|
| 865 |
+
# check whether manager is still alive
|
| 866 |
+
if state is None or state.value == State.STARTED:
|
| 867 |
+
# tell manager this process no longer cares about referent
|
| 868 |
+
try:
|
| 869 |
+
util.debug('DECREF %r', token.id)
|
| 870 |
+
conn = _Client(token.address, authkey=authkey)
|
| 871 |
+
dispatch(conn, None, 'decref', (token.id,))
|
| 872 |
+
except Exception as e:
|
| 873 |
+
util.debug('... decref failed %s', e)
|
| 874 |
+
|
| 875 |
+
else:
|
| 876 |
+
util.debug('DECREF %r -- manager already shutdown', token.id)
|
| 877 |
+
|
| 878 |
+
# check whether we can close this thread's connection because
|
| 879 |
+
# the process owns no more references to objects for this manager
|
| 880 |
+
if not idset and hasattr(tls, 'connection'):
|
| 881 |
+
util.debug('thread %r has no more proxies so closing conn',
|
| 882 |
+
threading.current_thread().name)
|
| 883 |
+
tls.connection.close()
|
| 884 |
+
del tls.connection
|
| 885 |
+
|
| 886 |
+
def _after_fork(self):
|
| 887 |
+
self._manager = None
|
| 888 |
+
try:
|
| 889 |
+
self._incref()
|
| 890 |
+
except Exception as e:
|
| 891 |
+
# the proxy may just be for a manager which has shutdown
|
| 892 |
+
util.info('incref failed: %s' % e)
|
| 893 |
+
|
| 894 |
+
def __reduce__(self):
|
| 895 |
+
kwds = {}
|
| 896 |
+
if get_spawning_popen() is not None:
|
| 897 |
+
kwds['authkey'] = self._authkey
|
| 898 |
+
|
| 899 |
+
if getattr(self, '_isauto', False):
|
| 900 |
+
kwds['exposed'] = self._exposed_
|
| 901 |
+
return (RebuildProxy,
|
| 902 |
+
(AutoProxy, self._token, self._serializer, kwds))
|
| 903 |
+
else:
|
| 904 |
+
return (RebuildProxy,
|
| 905 |
+
(type(self), self._token, self._serializer, kwds))
|
| 906 |
+
|
| 907 |
+
def __deepcopy__(self, memo):
|
| 908 |
+
return self._getvalue()
|
| 909 |
+
|
| 910 |
+
def __repr__(self):
|
| 911 |
+
return '<%s object, typeid %r at %#x>' % \
|
| 912 |
+
(type(self).__name__, self._token.typeid, id(self))
|
| 913 |
+
|
| 914 |
+
def __str__(self):
|
| 915 |
+
'''
|
| 916 |
+
Return representation of the referent (or a fall-back if that fails)
|
| 917 |
+
'''
|
| 918 |
+
try:
|
| 919 |
+
return self._callmethod('__repr__')
|
| 920 |
+
except Exception:
|
| 921 |
+
return repr(self)[:-1] + "; '__str__()' failed>"
|
| 922 |
+
|
| 923 |
+
#
|
| 924 |
+
# Function used for unpickling
|
| 925 |
+
#
|
| 926 |
+
|
| 927 |
+
def RebuildProxy(func, token, serializer, kwds):
|
| 928 |
+
'''
|
| 929 |
+
Function used for unpickling proxy objects.
|
| 930 |
+
'''
|
| 931 |
+
server = getattr(process.current_process(), '_manager_server', None)
|
| 932 |
+
if server and server.address == token.address:
|
| 933 |
+
util.debug('Rebuild a proxy owned by manager, token=%r', token)
|
| 934 |
+
kwds['manager_owned'] = True
|
| 935 |
+
if token.id not in server.id_to_local_proxy_obj:
|
| 936 |
+
server.id_to_local_proxy_obj[token.id] = \
|
| 937 |
+
server.id_to_obj[token.id]
|
| 938 |
+
incref = (
|
| 939 |
+
kwds.pop('incref', True) and
|
| 940 |
+
not getattr(process.current_process(), '_inheriting', False)
|
| 941 |
+
)
|
| 942 |
+
return func(token, serializer, incref=incref, **kwds)
|
| 943 |
+
|
| 944 |
+
#
|
| 945 |
+
# Functions to create proxies and proxy types
|
| 946 |
+
#
|
| 947 |
+
|
| 948 |
+
def MakeProxyType(name, exposed, _cache={}):
|
| 949 |
+
'''
|
| 950 |
+
Return a proxy type whose methods are given by `exposed`
|
| 951 |
+
'''
|
| 952 |
+
exposed = tuple(exposed)
|
| 953 |
+
try:
|
| 954 |
+
return _cache[(name, exposed)]
|
| 955 |
+
except KeyError:
|
| 956 |
+
pass
|
| 957 |
+
|
| 958 |
+
dic = {}
|
| 959 |
+
|
| 960 |
+
for meth in exposed:
|
| 961 |
+
exec('''def %s(self, /, *args, **kwds):
|
| 962 |
+
return self._callmethod(%r, args, kwds)''' % (meth, meth), dic)
|
| 963 |
+
|
| 964 |
+
ProxyType = type(name, (BaseProxy,), dic)
|
| 965 |
+
ProxyType._exposed_ = exposed
|
| 966 |
+
_cache[(name, exposed)] = ProxyType
|
| 967 |
+
return ProxyType
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def AutoProxy(token, serializer, manager=None, authkey=None,
|
| 971 |
+
exposed=None, incref=True, manager_owned=False):
|
| 972 |
+
'''
|
| 973 |
+
Return an auto-proxy for `token`
|
| 974 |
+
'''
|
| 975 |
+
_Client = listener_client[serializer][1]
|
| 976 |
+
|
| 977 |
+
if exposed is None:
|
| 978 |
+
conn = _Client(token.address, authkey=authkey)
|
| 979 |
+
try:
|
| 980 |
+
exposed = dispatch(conn, None, 'get_methods', (token,))
|
| 981 |
+
finally:
|
| 982 |
+
conn.close()
|
| 983 |
+
|
| 984 |
+
if authkey is None and manager is not None:
|
| 985 |
+
authkey = manager._authkey
|
| 986 |
+
if authkey is None:
|
| 987 |
+
authkey = process.current_process().authkey
|
| 988 |
+
|
| 989 |
+
ProxyType = MakeProxyType('AutoProxy[%s]' % token.typeid, exposed)
|
| 990 |
+
proxy = ProxyType(token, serializer, manager=manager, authkey=authkey,
|
| 991 |
+
incref=incref, manager_owned=manager_owned)
|
| 992 |
+
proxy._isauto = True
|
| 993 |
+
return proxy
|
| 994 |
+
|
| 995 |
+
#
|
| 996 |
+
# Types/callables which we will register with SyncManager
|
| 997 |
+
#
|
| 998 |
+
|
| 999 |
+
class Namespace(object):
|
| 1000 |
+
def __init__(self, /, **kwds):
|
| 1001 |
+
self.__dict__.update(kwds)
|
| 1002 |
+
def __repr__(self):
|
| 1003 |
+
items = list(self.__dict__.items())
|
| 1004 |
+
temp = []
|
| 1005 |
+
for name, value in items:
|
| 1006 |
+
if not name.startswith('_'):
|
| 1007 |
+
temp.append('%s=%r' % (name, value))
|
| 1008 |
+
temp.sort()
|
| 1009 |
+
return '%s(%s)' % (self.__class__.__name__, ', '.join(temp))
|
| 1010 |
+
|
| 1011 |
+
class Value(object):
|
| 1012 |
+
def __init__(self, typecode, value, lock=True):
|
| 1013 |
+
self._typecode = typecode
|
| 1014 |
+
self._value = value
|
| 1015 |
+
def get(self):
|
| 1016 |
+
return self._value
|
| 1017 |
+
def set(self, value):
|
| 1018 |
+
self._value = value
|
| 1019 |
+
def __repr__(self):
|
| 1020 |
+
return '%s(%r, %r)'%(type(self).__name__, self._typecode, self._value)
|
| 1021 |
+
value = property(get, set)
|
| 1022 |
+
|
| 1023 |
+
def Array(typecode, sequence, lock=True):
|
| 1024 |
+
return array.array(typecode, sequence)
|
| 1025 |
+
|
| 1026 |
+
#
|
| 1027 |
+
# Proxy types used by SyncManager
|
| 1028 |
+
#
|
| 1029 |
+
|
| 1030 |
+
class IteratorProxy(BaseProxy):
|
| 1031 |
+
_exposed_ = ('__next__', 'send', 'throw', 'close')
|
| 1032 |
+
def __iter__(self):
|
| 1033 |
+
return self
|
| 1034 |
+
def __next__(self, *args):
|
| 1035 |
+
return self._callmethod('__next__', args)
|
| 1036 |
+
def send(self, *args):
|
| 1037 |
+
return self._callmethod('send', args)
|
| 1038 |
+
def throw(self, *args):
|
| 1039 |
+
return self._callmethod('throw', args)
|
| 1040 |
+
def close(self, *args):
|
| 1041 |
+
return self._callmethod('close', args)
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
class AcquirerProxy(BaseProxy):
|
| 1045 |
+
_exposed_ = ('acquire', 'release')
|
| 1046 |
+
def acquire(self, blocking=True, timeout=None):
|
| 1047 |
+
args = (blocking,) if timeout is None else (blocking, timeout)
|
| 1048 |
+
return self._callmethod('acquire', args)
|
| 1049 |
+
def release(self):
|
| 1050 |
+
return self._callmethod('release')
|
| 1051 |
+
def __enter__(self):
|
| 1052 |
+
return self._callmethod('acquire')
|
| 1053 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 1054 |
+
return self._callmethod('release')
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
class ConditionProxy(AcquirerProxy):
|
| 1058 |
+
_exposed_ = ('acquire', 'release', 'wait', 'notify', 'notify_all')
|
| 1059 |
+
def wait(self, timeout=None):
|
| 1060 |
+
return self._callmethod('wait', (timeout,))
|
| 1061 |
+
def notify(self, n=1):
|
| 1062 |
+
return self._callmethod('notify', (n,))
|
| 1063 |
+
def notify_all(self):
|
| 1064 |
+
return self._callmethod('notify_all')
|
| 1065 |
+
def wait_for(self, predicate, timeout=None):
|
| 1066 |
+
result = predicate()
|
| 1067 |
+
if result:
|
| 1068 |
+
return result
|
| 1069 |
+
if timeout is not None:
|
| 1070 |
+
endtime = time.monotonic() + timeout
|
| 1071 |
+
else:
|
| 1072 |
+
endtime = None
|
| 1073 |
+
waittime = None
|
| 1074 |
+
while not result:
|
| 1075 |
+
if endtime is not None:
|
| 1076 |
+
waittime = endtime - time.monotonic()
|
| 1077 |
+
if waittime <= 0:
|
| 1078 |
+
break
|
| 1079 |
+
self.wait(waittime)
|
| 1080 |
+
result = predicate()
|
| 1081 |
+
return result
|
| 1082 |
+
|
| 1083 |
+
|
| 1084 |
+
class EventProxy(BaseProxy):
|
| 1085 |
+
_exposed_ = ('is_set', 'set', 'clear', 'wait')
|
| 1086 |
+
def is_set(self):
|
| 1087 |
+
return self._callmethod('is_set')
|
| 1088 |
+
def set(self):
|
| 1089 |
+
return self._callmethod('set')
|
| 1090 |
+
def clear(self):
|
| 1091 |
+
return self._callmethod('clear')
|
| 1092 |
+
def wait(self, timeout=None):
|
| 1093 |
+
return self._callmethod('wait', (timeout,))
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
class BarrierProxy(BaseProxy):
|
| 1097 |
+
_exposed_ = ('__getattribute__', 'wait', 'abort', 'reset')
|
| 1098 |
+
def wait(self, timeout=None):
|
| 1099 |
+
return self._callmethod('wait', (timeout,))
|
| 1100 |
+
def abort(self):
|
| 1101 |
+
return self._callmethod('abort')
|
| 1102 |
+
def reset(self):
|
| 1103 |
+
return self._callmethod('reset')
|
| 1104 |
+
@property
|
| 1105 |
+
def parties(self):
|
| 1106 |
+
return self._callmethod('__getattribute__', ('parties',))
|
| 1107 |
+
@property
|
| 1108 |
+
def n_waiting(self):
|
| 1109 |
+
return self._callmethod('__getattribute__', ('n_waiting',))
|
| 1110 |
+
@property
|
| 1111 |
+
def broken(self):
|
| 1112 |
+
return self._callmethod('__getattribute__', ('broken',))
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
class NamespaceProxy(BaseProxy):
|
| 1116 |
+
_exposed_ = ('__getattribute__', '__setattr__', '__delattr__')
|
| 1117 |
+
def __getattr__(self, key):
|
| 1118 |
+
if key[0] == '_':
|
| 1119 |
+
return object.__getattribute__(self, key)
|
| 1120 |
+
callmethod = object.__getattribute__(self, '_callmethod')
|
| 1121 |
+
return callmethod('__getattribute__', (key,))
|
| 1122 |
+
def __setattr__(self, key, value):
|
| 1123 |
+
if key[0] == '_':
|
| 1124 |
+
return object.__setattr__(self, key, value)
|
| 1125 |
+
callmethod = object.__getattribute__(self, '_callmethod')
|
| 1126 |
+
return callmethod('__setattr__', (key, value))
|
| 1127 |
+
def __delattr__(self, key):
|
| 1128 |
+
if key[0] == '_':
|
| 1129 |
+
return object.__delattr__(self, key)
|
| 1130 |
+
callmethod = object.__getattribute__(self, '_callmethod')
|
| 1131 |
+
return callmethod('__delattr__', (key,))
|
| 1132 |
+
|
| 1133 |
+
|
| 1134 |
+
class ValueProxy(BaseProxy):
|
| 1135 |
+
_exposed_ = ('get', 'set')
|
| 1136 |
+
def get(self):
|
| 1137 |
+
return self._callmethod('get')
|
| 1138 |
+
def set(self, value):
|
| 1139 |
+
return self._callmethod('set', (value,))
|
| 1140 |
+
value = property(get, set)
|
| 1141 |
+
|
| 1142 |
+
__class_getitem__ = classmethod(types.GenericAlias)
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
BaseListProxy = MakeProxyType('BaseListProxy', (
|
| 1146 |
+
'__add__', '__contains__', '__delitem__', '__getitem__', '__len__',
|
| 1147 |
+
'__mul__', '__reversed__', '__rmul__', '__setitem__',
|
| 1148 |
+
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
|
| 1149 |
+
'reverse', 'sort', '__imul__'
|
| 1150 |
+
))
|
| 1151 |
+
class ListProxy(BaseListProxy):
|
| 1152 |
+
def __iadd__(self, value):
|
| 1153 |
+
self._callmethod('extend', (value,))
|
| 1154 |
+
return self
|
| 1155 |
+
def __imul__(self, value):
|
| 1156 |
+
self._callmethod('__imul__', (value,))
|
| 1157 |
+
return self
|
| 1158 |
+
|
| 1159 |
+
|
| 1160 |
+
DictProxy = MakeProxyType('DictProxy', (
|
| 1161 |
+
'__contains__', '__delitem__', '__getitem__', '__iter__', '__len__',
|
| 1162 |
+
'__setitem__', 'clear', 'copy', 'get', 'items',
|
| 1163 |
+
'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'
|
| 1164 |
+
))
|
| 1165 |
+
DictProxy._method_to_typeid_ = {
|
| 1166 |
+
'__iter__': 'Iterator',
|
| 1167 |
+
}
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
ArrayProxy = MakeProxyType('ArrayProxy', (
|
| 1171 |
+
'__len__', '__getitem__', '__setitem__'
|
| 1172 |
+
))
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
BasePoolProxy = MakeProxyType('PoolProxy', (
|
| 1176 |
+
'apply', 'apply_async', 'close', 'imap', 'imap_unordered', 'join',
|
| 1177 |
+
'map', 'map_async', 'starmap', 'starmap_async', 'terminate',
|
| 1178 |
+
))
|
| 1179 |
+
BasePoolProxy._method_to_typeid_ = {
|
| 1180 |
+
'apply_async': 'AsyncResult',
|
| 1181 |
+
'map_async': 'AsyncResult',
|
| 1182 |
+
'starmap_async': 'AsyncResult',
|
| 1183 |
+
'imap': 'Iterator',
|
| 1184 |
+
'imap_unordered': 'Iterator'
|
| 1185 |
+
}
|
| 1186 |
+
class PoolProxy(BasePoolProxy):
|
| 1187 |
+
def __enter__(self):
|
| 1188 |
+
return self
|
| 1189 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 1190 |
+
self.terminate()
|
| 1191 |
+
|
| 1192 |
+
#
|
| 1193 |
+
# Definition of SyncManager
|
| 1194 |
+
#
|
| 1195 |
+
|
| 1196 |
+
class SyncManager(BaseManager):
|
| 1197 |
+
'''
|
| 1198 |
+
Subclass of `BaseManager` which supports a number of shared object types.
|
| 1199 |
+
|
| 1200 |
+
The types registered are those intended for the synchronization
|
| 1201 |
+
of threads, plus `dict`, `list` and `Namespace`.
|
| 1202 |
+
|
| 1203 |
+
The `multiprocessing.Manager()` function creates started instances of
|
| 1204 |
+
this class.
|
| 1205 |
+
'''
|
| 1206 |
+
|
| 1207 |
+
SyncManager.register('Queue', queue.Queue)
|
| 1208 |
+
SyncManager.register('JoinableQueue', queue.Queue)
|
| 1209 |
+
SyncManager.register('Event', threading.Event, EventProxy)
|
| 1210 |
+
SyncManager.register('Lock', threading.Lock, AcquirerProxy)
|
| 1211 |
+
SyncManager.register('RLock', threading.RLock, AcquirerProxy)
|
| 1212 |
+
SyncManager.register('Semaphore', threading.Semaphore, AcquirerProxy)
|
| 1213 |
+
SyncManager.register('BoundedSemaphore', threading.BoundedSemaphore,
|
| 1214 |
+
AcquirerProxy)
|
| 1215 |
+
SyncManager.register('Condition', threading.Condition, ConditionProxy)
|
| 1216 |
+
SyncManager.register('Barrier', threading.Barrier, BarrierProxy)
|
| 1217 |
+
SyncManager.register('Pool', pool.Pool, PoolProxy)
|
| 1218 |
+
SyncManager.register('list', list, ListProxy)
|
| 1219 |
+
SyncManager.register('dict', dict, DictProxy)
|
| 1220 |
+
SyncManager.register('Value', Value, ValueProxy)
|
| 1221 |
+
SyncManager.register('Array', Array, ArrayProxy)
|
| 1222 |
+
SyncManager.register('Namespace', Namespace, NamespaceProxy)
|
| 1223 |
+
|
| 1224 |
+
# types returned by methods of PoolProxy
|
| 1225 |
+
SyncManager.register('Iterator', proxytype=IteratorProxy, create_method=False)
|
| 1226 |
+
SyncManager.register('AsyncResult', create_method=False)
|
| 1227 |
+
|
| 1228 |
+
#
|
| 1229 |
+
# Definition of SharedMemoryManager and SharedMemoryServer
|
| 1230 |
+
#
|
| 1231 |
+
|
| 1232 |
+
if HAS_SHMEM:
|
| 1233 |
+
class _SharedMemoryTracker:
|
| 1234 |
+
"Manages one or more shared memory segments."
|
| 1235 |
+
|
| 1236 |
+
def __init__(self, name, segment_names=[]):
|
| 1237 |
+
self.shared_memory_context_name = name
|
| 1238 |
+
self.segment_names = segment_names
|
| 1239 |
+
|
| 1240 |
+
def register_segment(self, segment_name):
|
| 1241 |
+
"Adds the supplied shared memory block name to tracker."
|
| 1242 |
+
util.debug(f"Register segment {segment_name!r} in pid {getpid()}")
|
| 1243 |
+
self.segment_names.append(segment_name)
|
| 1244 |
+
|
| 1245 |
+
def destroy_segment(self, segment_name):
|
| 1246 |
+
"""Calls unlink() on the shared memory block with the supplied name
|
| 1247 |
+
and removes it from the list of blocks being tracked."""
|
| 1248 |
+
util.debug(f"Destroy segment {segment_name!r} in pid {getpid()}")
|
| 1249 |
+
self.segment_names.remove(segment_name)
|
| 1250 |
+
segment = shared_memory.SharedMemory(segment_name)
|
| 1251 |
+
segment.close()
|
| 1252 |
+
segment.unlink()
|
| 1253 |
+
|
| 1254 |
+
def unlink(self):
|
| 1255 |
+
"Calls destroy_segment() on all tracked shared memory blocks."
|
| 1256 |
+
for segment_name in self.segment_names[:]:
|
| 1257 |
+
self.destroy_segment(segment_name)
|
| 1258 |
+
|
| 1259 |
+
def __del__(self):
|
| 1260 |
+
util.debug(f"Call {self.__class__.__name__}.__del__ in {getpid()}")
|
| 1261 |
+
self.unlink()
|
| 1262 |
+
|
| 1263 |
+
def __getstate__(self):
|
| 1264 |
+
return (self.shared_memory_context_name, self.segment_names)
|
| 1265 |
+
|
| 1266 |
+
def __setstate__(self, state):
|
| 1267 |
+
self.__init__(*state)
|
| 1268 |
+
|
| 1269 |
+
|
| 1270 |
+
class SharedMemoryServer(Server):
|
| 1271 |
+
|
| 1272 |
+
public = Server.public + \
|
| 1273 |
+
['track_segment', 'release_segment', 'list_segments']
|
| 1274 |
+
|
| 1275 |
+
def __init__(self, *args, **kwargs):
|
| 1276 |
+
Server.__init__(self, *args, **kwargs)
|
| 1277 |
+
address = self.address
|
| 1278 |
+
# The address of Linux abstract namespaces can be bytes
|
| 1279 |
+
if isinstance(address, bytes):
|
| 1280 |
+
address = os.fsdecode(address)
|
| 1281 |
+
self.shared_memory_context = \
|
| 1282 |
+
_SharedMemoryTracker(f"shm_{address}_{getpid()}")
|
| 1283 |
+
util.debug(f"SharedMemoryServer started by pid {getpid()}")
|
| 1284 |
+
|
| 1285 |
+
def create(self, c, typeid, /, *args, **kwargs):
|
| 1286 |
+
"""Create a new distributed-shared object (not backed by a shared
|
| 1287 |
+
memory block) and return its id to be used in a Proxy Object."""
|
| 1288 |
+
# Unless set up as a shared proxy, don't make shared_memory_context
|
| 1289 |
+
# a standard part of kwargs. This makes things easier for supplying
|
| 1290 |
+
# simple functions.
|
| 1291 |
+
if hasattr(self.registry[typeid][-1], "_shared_memory_proxy"):
|
| 1292 |
+
kwargs['shared_memory_context'] = self.shared_memory_context
|
| 1293 |
+
return Server.create(self, c, typeid, *args, **kwargs)
|
| 1294 |
+
|
| 1295 |
+
def shutdown(self, c):
|
| 1296 |
+
"Call unlink() on all tracked shared memory, terminate the Server."
|
| 1297 |
+
self.shared_memory_context.unlink()
|
| 1298 |
+
return Server.shutdown(self, c)
|
| 1299 |
+
|
| 1300 |
+
def track_segment(self, c, segment_name):
|
| 1301 |
+
"Adds the supplied shared memory block name to Server's tracker."
|
| 1302 |
+
self.shared_memory_context.register_segment(segment_name)
|
| 1303 |
+
|
| 1304 |
+
def release_segment(self, c, segment_name):
|
| 1305 |
+
"""Calls unlink() on the shared memory block with the supplied name
|
| 1306 |
+
and removes it from the tracker instance inside the Server."""
|
| 1307 |
+
self.shared_memory_context.destroy_segment(segment_name)
|
| 1308 |
+
|
| 1309 |
+
def list_segments(self, c):
|
| 1310 |
+
"""Returns a list of names of shared memory blocks that the Server
|
| 1311 |
+
is currently tracking."""
|
| 1312 |
+
return self.shared_memory_context.segment_names
|
| 1313 |
+
|
| 1314 |
+
|
| 1315 |
+
class SharedMemoryManager(BaseManager):
|
| 1316 |
+
"""Like SyncManager but uses SharedMemoryServer instead of Server.
|
| 1317 |
+
|
| 1318 |
+
It provides methods for creating and returning SharedMemory instances
|
| 1319 |
+
and for creating a list-like object (ShareableList) backed by shared
|
| 1320 |
+
memory. It also provides methods that create and return Proxy Objects
|
| 1321 |
+
that support synchronization across processes (i.e. multi-process-safe
|
| 1322 |
+
locks and semaphores).
|
| 1323 |
+
"""
|
| 1324 |
+
|
| 1325 |
+
_Server = SharedMemoryServer
|
| 1326 |
+
|
| 1327 |
+
def __init__(self, *args, **kwargs):
|
| 1328 |
+
if os.name == "posix":
|
| 1329 |
+
# bpo-36867: Ensure the resource_tracker is running before
|
| 1330 |
+
# launching the manager process, so that concurrent
|
| 1331 |
+
# shared_memory manipulation both in the manager and in the
|
| 1332 |
+
# current process does not create two resource_tracker
|
| 1333 |
+
# processes.
|
| 1334 |
+
from . import resource_tracker
|
| 1335 |
+
resource_tracker.ensure_running()
|
| 1336 |
+
BaseManager.__init__(self, *args, **kwargs)
|
| 1337 |
+
util.debug(f"{self.__class__.__name__} created by pid {getpid()}")
|
| 1338 |
+
|
| 1339 |
+
def __del__(self):
|
| 1340 |
+
util.debug(f"{self.__class__.__name__}.__del__ by pid {getpid()}")
|
| 1341 |
+
pass
|
| 1342 |
+
|
| 1343 |
+
def get_server(self):
|
| 1344 |
+
'Better than monkeypatching for now; merge into Server ultimately'
|
| 1345 |
+
if self._state.value != State.INITIAL:
|
| 1346 |
+
if self._state.value == State.STARTED:
|
| 1347 |
+
raise ProcessError("Already started SharedMemoryServer")
|
| 1348 |
+
elif self._state.value == State.SHUTDOWN:
|
| 1349 |
+
raise ProcessError("SharedMemoryManager has shut down")
|
| 1350 |
+
else:
|
| 1351 |
+
raise ProcessError(
|
| 1352 |
+
"Unknown state {!r}".format(self._state.value))
|
| 1353 |
+
return self._Server(self._registry, self._address,
|
| 1354 |
+
self._authkey, self._serializer)
|
| 1355 |
+
|
| 1356 |
+
def SharedMemory(self, size):
|
| 1357 |
+
"""Returns a new SharedMemory instance with the specified size in
|
| 1358 |
+
bytes, to be tracked by the manager."""
|
| 1359 |
+
with self._Client(self._address, authkey=self._authkey) as conn:
|
| 1360 |
+
sms = shared_memory.SharedMemory(None, create=True, size=size)
|
| 1361 |
+
try:
|
| 1362 |
+
dispatch(conn, None, 'track_segment', (sms.name,))
|
| 1363 |
+
except BaseException as e:
|
| 1364 |
+
sms.unlink()
|
| 1365 |
+
raise e
|
| 1366 |
+
return sms
|
| 1367 |
+
|
| 1368 |
+
def ShareableList(self, sequence):
|
| 1369 |
+
"""Returns a new ShareableList instance populated with the values
|
| 1370 |
+
from the input sequence, to be tracked by the manager."""
|
| 1371 |
+
with self._Client(self._address, authkey=self._authkey) as conn:
|
| 1372 |
+
sl = shared_memory.ShareableList(sequence)
|
| 1373 |
+
try:
|
| 1374 |
+
dispatch(conn, None, 'track_segment', (sl.shm.name,))
|
| 1375 |
+
except BaseException as e:
|
| 1376 |
+
sl.shm.unlink()
|
| 1377 |
+
raise e
|
| 1378 |
+
return sl
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Module providing the `Pool` class for managing a process pool
|
| 3 |
+
#
|
| 4 |
+
# multiprocessing/pool.py
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2006-2008, R Oudkerk
|
| 7 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 8 |
+
#
|
| 9 |
+
|
| 10 |
+
__all__ = ['Pool', 'ThreadPool']
|
| 11 |
+
|
| 12 |
+
#
|
| 13 |
+
# Imports
|
| 14 |
+
#
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
import itertools
|
| 18 |
+
import os
|
| 19 |
+
import queue
|
| 20 |
+
import threading
|
| 21 |
+
import time
|
| 22 |
+
import traceback
|
| 23 |
+
import types
|
| 24 |
+
import warnings
|
| 25 |
+
|
| 26 |
+
# If threading is available then ThreadPool should be provided. Therefore
|
| 27 |
+
# we avoid top-level imports which are liable to fail on some systems.
|
| 28 |
+
from . import util
|
| 29 |
+
from . import get_context, TimeoutError
|
| 30 |
+
from .connection import wait
|
| 31 |
+
|
| 32 |
+
#
|
| 33 |
+
# Constants representing the state of a pool
|
| 34 |
+
#
|
| 35 |
+
|
| 36 |
+
INIT = "INIT"
|
| 37 |
+
RUN = "RUN"
|
| 38 |
+
CLOSE = "CLOSE"
|
| 39 |
+
TERMINATE = "TERMINATE"
|
| 40 |
+
|
| 41 |
+
#
|
| 42 |
+
# Miscellaneous
|
| 43 |
+
#
|
| 44 |
+
|
| 45 |
+
job_counter = itertools.count()
|
| 46 |
+
|
| 47 |
+
def mapstar(args):
|
| 48 |
+
return list(map(*args))
|
| 49 |
+
|
| 50 |
+
def starmapstar(args):
|
| 51 |
+
return list(itertools.starmap(args[0], args[1]))
|
| 52 |
+
|
| 53 |
+
#
|
| 54 |
+
# Hack to embed stringification of remote traceback in local traceback
|
| 55 |
+
#
|
| 56 |
+
|
| 57 |
+
class RemoteTraceback(Exception):
|
| 58 |
+
def __init__(self, tb):
|
| 59 |
+
self.tb = tb
|
| 60 |
+
def __str__(self):
|
| 61 |
+
return self.tb
|
| 62 |
+
|
| 63 |
+
class ExceptionWithTraceback:
|
| 64 |
+
def __init__(self, exc, tb):
|
| 65 |
+
tb = traceback.format_exception(type(exc), exc, tb)
|
| 66 |
+
tb = ''.join(tb)
|
| 67 |
+
self.exc = exc
|
| 68 |
+
self.tb = '\n"""\n%s"""' % tb
|
| 69 |
+
def __reduce__(self):
|
| 70 |
+
return rebuild_exc, (self.exc, self.tb)
|
| 71 |
+
|
| 72 |
+
def rebuild_exc(exc, tb):
|
| 73 |
+
exc.__cause__ = RemoteTraceback(tb)
|
| 74 |
+
return exc
|
| 75 |
+
|
| 76 |
+
#
|
| 77 |
+
# Code run by worker processes
|
| 78 |
+
#
|
| 79 |
+
|
| 80 |
+
class MaybeEncodingError(Exception):
|
| 81 |
+
"""Wraps possible unpickleable errors, so they can be
|
| 82 |
+
safely sent through the socket."""
|
| 83 |
+
|
| 84 |
+
def __init__(self, exc, value):
|
| 85 |
+
self.exc = repr(exc)
|
| 86 |
+
self.value = repr(value)
|
| 87 |
+
super(MaybeEncodingError, self).__init__(self.exc, self.value)
|
| 88 |
+
|
| 89 |
+
def __str__(self):
|
| 90 |
+
return "Error sending result: '%s'. Reason: '%s'" % (self.value,
|
| 91 |
+
self.exc)
|
| 92 |
+
|
| 93 |
+
def __repr__(self):
|
| 94 |
+
return "<%s: %s>" % (self.__class__.__name__, self)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None,
|
| 98 |
+
wrap_exception=False):
|
| 99 |
+
if (maxtasks is not None) and not (isinstance(maxtasks, int)
|
| 100 |
+
and maxtasks >= 1):
|
| 101 |
+
raise AssertionError("Maxtasks {!r} is not valid".format(maxtasks))
|
| 102 |
+
put = outqueue.put
|
| 103 |
+
get = inqueue.get
|
| 104 |
+
if hasattr(inqueue, '_writer'):
|
| 105 |
+
inqueue._writer.close()
|
| 106 |
+
outqueue._reader.close()
|
| 107 |
+
|
| 108 |
+
if initializer is not None:
|
| 109 |
+
initializer(*initargs)
|
| 110 |
+
|
| 111 |
+
completed = 0
|
| 112 |
+
while maxtasks is None or (maxtasks and completed < maxtasks):
|
| 113 |
+
try:
|
| 114 |
+
task = get()
|
| 115 |
+
except (EOFError, OSError):
|
| 116 |
+
util.debug('worker got EOFError or OSError -- exiting')
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
if task is None:
|
| 120 |
+
util.debug('worker got sentinel -- exiting')
|
| 121 |
+
break
|
| 122 |
+
|
| 123 |
+
job, i, func, args, kwds = task
|
| 124 |
+
try:
|
| 125 |
+
result = (True, func(*args, **kwds))
|
| 126 |
+
except Exception as e:
|
| 127 |
+
if wrap_exception and func is not _helper_reraises_exception:
|
| 128 |
+
e = ExceptionWithTraceback(e, e.__traceback__)
|
| 129 |
+
result = (False, e)
|
| 130 |
+
try:
|
| 131 |
+
put((job, i, result))
|
| 132 |
+
except Exception as e:
|
| 133 |
+
wrapped = MaybeEncodingError(e, result[1])
|
| 134 |
+
util.debug("Possible encoding error while sending result: %s" % (
|
| 135 |
+
wrapped))
|
| 136 |
+
put((job, i, (False, wrapped)))
|
| 137 |
+
|
| 138 |
+
task = job = result = func = args = kwds = None
|
| 139 |
+
completed += 1
|
| 140 |
+
util.debug('worker exiting after %d tasks' % completed)
|
| 141 |
+
|
| 142 |
+
def _helper_reraises_exception(ex):
|
| 143 |
+
'Pickle-able helper function for use by _guarded_task_generation.'
|
| 144 |
+
raise ex
|
| 145 |
+
|
| 146 |
+
#
|
| 147 |
+
# Class representing a process pool
|
| 148 |
+
#
|
| 149 |
+
|
| 150 |
+
class _PoolCache(dict):
|
| 151 |
+
"""
|
| 152 |
+
Class that implements a cache for the Pool class that will notify
|
| 153 |
+
the pool management threads every time the cache is emptied. The
|
| 154 |
+
notification is done by the use of a queue that is provided when
|
| 155 |
+
instantiating the cache.
|
| 156 |
+
"""
|
| 157 |
+
def __init__(self, /, *args, notifier=None, **kwds):
|
| 158 |
+
self.notifier = notifier
|
| 159 |
+
super().__init__(*args, **kwds)
|
| 160 |
+
|
| 161 |
+
def __delitem__(self, item):
|
| 162 |
+
super().__delitem__(item)
|
| 163 |
+
|
| 164 |
+
# Notify that the cache is empty. This is important because the
|
| 165 |
+
# pool keeps maintaining workers until the cache gets drained. This
|
| 166 |
+
# eliminates a race condition in which a task is finished after the
|
| 167 |
+
# the pool's _handle_workers method has enter another iteration of the
|
| 168 |
+
# loop. In this situation, the only event that can wake up the pool
|
| 169 |
+
# is the cache to be emptied (no more tasks available).
|
| 170 |
+
if not self:
|
| 171 |
+
self.notifier.put(None)
|
| 172 |
+
|
| 173 |
+
class Pool(object):
|
| 174 |
+
'''
|
| 175 |
+
Class which supports an async version of applying functions to arguments.
|
| 176 |
+
'''
|
| 177 |
+
_wrap_exception = True
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def Process(ctx, *args, **kwds):
|
| 181 |
+
return ctx.Process(*args, **kwds)
|
| 182 |
+
|
| 183 |
+
def __init__(self, processes=None, initializer=None, initargs=(),
|
| 184 |
+
maxtasksperchild=None, context=None):
|
| 185 |
+
# Attributes initialized early to make sure that they exist in
|
| 186 |
+
# __del__() if __init__() raises an exception
|
| 187 |
+
self._pool = []
|
| 188 |
+
self._state = INIT
|
| 189 |
+
|
| 190 |
+
self._ctx = context or get_context()
|
| 191 |
+
self._setup_queues()
|
| 192 |
+
self._taskqueue = queue.SimpleQueue()
|
| 193 |
+
# The _change_notifier queue exist to wake up self._handle_workers()
|
| 194 |
+
# when the cache (self._cache) is empty or when there is a change in
|
| 195 |
+
# the _state variable of the thread that runs _handle_workers.
|
| 196 |
+
self._change_notifier = self._ctx.SimpleQueue()
|
| 197 |
+
self._cache = _PoolCache(notifier=self._change_notifier)
|
| 198 |
+
self._maxtasksperchild = maxtasksperchild
|
| 199 |
+
self._initializer = initializer
|
| 200 |
+
self._initargs = initargs
|
| 201 |
+
|
| 202 |
+
if processes is None:
|
| 203 |
+
processes = os.cpu_count() or 1
|
| 204 |
+
if processes < 1:
|
| 205 |
+
raise ValueError("Number of processes must be at least 1")
|
| 206 |
+
if maxtasksperchild is not None:
|
| 207 |
+
if not isinstance(maxtasksperchild, int) or maxtasksperchild <= 0:
|
| 208 |
+
raise ValueError("maxtasksperchild must be a positive int or None")
|
| 209 |
+
|
| 210 |
+
if initializer is not None and not callable(initializer):
|
| 211 |
+
raise TypeError('initializer must be a callable')
|
| 212 |
+
|
| 213 |
+
self._processes = processes
|
| 214 |
+
try:
|
| 215 |
+
self._repopulate_pool()
|
| 216 |
+
except Exception:
|
| 217 |
+
for p in self._pool:
|
| 218 |
+
if p.exitcode is None:
|
| 219 |
+
p.terminate()
|
| 220 |
+
for p in self._pool:
|
| 221 |
+
p.join()
|
| 222 |
+
raise
|
| 223 |
+
|
| 224 |
+
sentinels = self._get_sentinels()
|
| 225 |
+
|
| 226 |
+
self._worker_handler = threading.Thread(
|
| 227 |
+
target=Pool._handle_workers,
|
| 228 |
+
args=(self._cache, self._taskqueue, self._ctx, self.Process,
|
| 229 |
+
self._processes, self._pool, self._inqueue, self._outqueue,
|
| 230 |
+
self._initializer, self._initargs, self._maxtasksperchild,
|
| 231 |
+
self._wrap_exception, sentinels, self._change_notifier)
|
| 232 |
+
)
|
| 233 |
+
self._worker_handler.daemon = True
|
| 234 |
+
self._worker_handler._state = RUN
|
| 235 |
+
self._worker_handler.start()
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
self._task_handler = threading.Thread(
|
| 239 |
+
target=Pool._handle_tasks,
|
| 240 |
+
args=(self._taskqueue, self._quick_put, self._outqueue,
|
| 241 |
+
self._pool, self._cache)
|
| 242 |
+
)
|
| 243 |
+
self._task_handler.daemon = True
|
| 244 |
+
self._task_handler._state = RUN
|
| 245 |
+
self._task_handler.start()
|
| 246 |
+
|
| 247 |
+
self._result_handler = threading.Thread(
|
| 248 |
+
target=Pool._handle_results,
|
| 249 |
+
args=(self._outqueue, self._quick_get, self._cache)
|
| 250 |
+
)
|
| 251 |
+
self._result_handler.daemon = True
|
| 252 |
+
self._result_handler._state = RUN
|
| 253 |
+
self._result_handler.start()
|
| 254 |
+
|
| 255 |
+
self._terminate = util.Finalize(
|
| 256 |
+
self, self._terminate_pool,
|
| 257 |
+
args=(self._taskqueue, self._inqueue, self._outqueue, self._pool,
|
| 258 |
+
self._change_notifier, self._worker_handler, self._task_handler,
|
| 259 |
+
self._result_handler, self._cache),
|
| 260 |
+
exitpriority=15
|
| 261 |
+
)
|
| 262 |
+
self._state = RUN
|
| 263 |
+
|
| 264 |
+
# Copy globals as function locals to make sure that they are available
|
| 265 |
+
# during Python shutdown when the Pool is destroyed.
|
| 266 |
+
def __del__(self, _warn=warnings.warn, RUN=RUN):
|
| 267 |
+
if self._state == RUN:
|
| 268 |
+
_warn(f"unclosed running multiprocessing pool {self!r}",
|
| 269 |
+
ResourceWarning, source=self)
|
| 270 |
+
if getattr(self, '_change_notifier', None) is not None:
|
| 271 |
+
self._change_notifier.put(None)
|
| 272 |
+
|
| 273 |
+
def __repr__(self):
|
| 274 |
+
cls = self.__class__
|
| 275 |
+
return (f'<{cls.__module__}.{cls.__qualname__} '
|
| 276 |
+
f'state={self._state} '
|
| 277 |
+
f'pool_size={len(self._pool)}>')
|
| 278 |
+
|
| 279 |
+
def _get_sentinels(self):
|
| 280 |
+
task_queue_sentinels = [self._outqueue._reader]
|
| 281 |
+
self_notifier_sentinels = [self._change_notifier._reader]
|
| 282 |
+
return [*task_queue_sentinels, *self_notifier_sentinels]
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def _get_worker_sentinels(workers):
|
| 286 |
+
return [worker.sentinel for worker in
|
| 287 |
+
workers if hasattr(worker, "sentinel")]
|
| 288 |
+
|
| 289 |
+
@staticmethod
|
| 290 |
+
def _join_exited_workers(pool):
|
| 291 |
+
"""Cleanup after any worker processes which have exited due to reaching
|
| 292 |
+
their specified lifetime. Returns True if any workers were cleaned up.
|
| 293 |
+
"""
|
| 294 |
+
cleaned = False
|
| 295 |
+
for i in reversed(range(len(pool))):
|
| 296 |
+
worker = pool[i]
|
| 297 |
+
if worker.exitcode is not None:
|
| 298 |
+
# worker exited
|
| 299 |
+
util.debug('cleaning up worker %d' % i)
|
| 300 |
+
worker.join()
|
| 301 |
+
cleaned = True
|
| 302 |
+
del pool[i]
|
| 303 |
+
return cleaned
|
| 304 |
+
|
| 305 |
+
def _repopulate_pool(self):
|
| 306 |
+
return self._repopulate_pool_static(self._ctx, self.Process,
|
| 307 |
+
self._processes,
|
| 308 |
+
self._pool, self._inqueue,
|
| 309 |
+
self._outqueue, self._initializer,
|
| 310 |
+
self._initargs,
|
| 311 |
+
self._maxtasksperchild,
|
| 312 |
+
self._wrap_exception)
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def _repopulate_pool_static(ctx, Process, processes, pool, inqueue,
|
| 316 |
+
outqueue, initializer, initargs,
|
| 317 |
+
maxtasksperchild, wrap_exception):
|
| 318 |
+
"""Bring the number of pool processes up to the specified number,
|
| 319 |
+
for use after reaping workers which have exited.
|
| 320 |
+
"""
|
| 321 |
+
for i in range(processes - len(pool)):
|
| 322 |
+
w = Process(ctx, target=worker,
|
| 323 |
+
args=(inqueue, outqueue,
|
| 324 |
+
initializer,
|
| 325 |
+
initargs, maxtasksperchild,
|
| 326 |
+
wrap_exception))
|
| 327 |
+
w.name = w.name.replace('Process', 'PoolWorker')
|
| 328 |
+
w.daemon = True
|
| 329 |
+
w.start()
|
| 330 |
+
pool.append(w)
|
| 331 |
+
util.debug('added worker')
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
def _maintain_pool(ctx, Process, processes, pool, inqueue, outqueue,
|
| 335 |
+
initializer, initargs, maxtasksperchild,
|
| 336 |
+
wrap_exception):
|
| 337 |
+
"""Clean up any exited workers and start replacements for them.
|
| 338 |
+
"""
|
| 339 |
+
if Pool._join_exited_workers(pool):
|
| 340 |
+
Pool._repopulate_pool_static(ctx, Process, processes, pool,
|
| 341 |
+
inqueue, outqueue, initializer,
|
| 342 |
+
initargs, maxtasksperchild,
|
| 343 |
+
wrap_exception)
|
| 344 |
+
|
| 345 |
+
def _setup_queues(self):
|
| 346 |
+
self._inqueue = self._ctx.SimpleQueue()
|
| 347 |
+
self._outqueue = self._ctx.SimpleQueue()
|
| 348 |
+
self._quick_put = self._inqueue._writer.send
|
| 349 |
+
self._quick_get = self._outqueue._reader.recv
|
| 350 |
+
|
| 351 |
+
def _check_running(self):
|
| 352 |
+
if self._state != RUN:
|
| 353 |
+
raise ValueError("Pool not running")
|
| 354 |
+
|
| 355 |
+
def apply(self, func, args=(), kwds={}):
|
| 356 |
+
'''
|
| 357 |
+
Equivalent of `func(*args, **kwds)`.
|
| 358 |
+
Pool must be running.
|
| 359 |
+
'''
|
| 360 |
+
return self.apply_async(func, args, kwds).get()
|
| 361 |
+
|
| 362 |
+
def map(self, func, iterable, chunksize=None):
|
| 363 |
+
'''
|
| 364 |
+
Apply `func` to each element in `iterable`, collecting the results
|
| 365 |
+
in a list that is returned.
|
| 366 |
+
'''
|
| 367 |
+
return self._map_async(func, iterable, mapstar, chunksize).get()
|
| 368 |
+
|
| 369 |
+
def starmap(self, func, iterable, chunksize=None):
|
| 370 |
+
'''
|
| 371 |
+
Like `map()` method but the elements of the `iterable` are expected to
|
| 372 |
+
be iterables as well and will be unpacked as arguments. Hence
|
| 373 |
+
`func` and (a, b) becomes func(a, b).
|
| 374 |
+
'''
|
| 375 |
+
return self._map_async(func, iterable, starmapstar, chunksize).get()
|
| 376 |
+
|
| 377 |
+
def starmap_async(self, func, iterable, chunksize=None, callback=None,
|
| 378 |
+
error_callback=None):
|
| 379 |
+
'''
|
| 380 |
+
Asynchronous version of `starmap()` method.
|
| 381 |
+
'''
|
| 382 |
+
return self._map_async(func, iterable, starmapstar, chunksize,
|
| 383 |
+
callback, error_callback)
|
| 384 |
+
|
| 385 |
+
def _guarded_task_generation(self, result_job, func, iterable):
|
| 386 |
+
'''Provides a generator of tasks for imap and imap_unordered with
|
| 387 |
+
appropriate handling for iterables which throw exceptions during
|
| 388 |
+
iteration.'''
|
| 389 |
+
try:
|
| 390 |
+
i = -1
|
| 391 |
+
for i, x in enumerate(iterable):
|
| 392 |
+
yield (result_job, i, func, (x,), {})
|
| 393 |
+
except Exception as e:
|
| 394 |
+
yield (result_job, i+1, _helper_reraises_exception, (e,), {})
|
| 395 |
+
|
| 396 |
+
def imap(self, func, iterable, chunksize=1):
|
| 397 |
+
'''
|
| 398 |
+
Equivalent of `map()` -- can be MUCH slower than `Pool.map()`.
|
| 399 |
+
'''
|
| 400 |
+
self._check_running()
|
| 401 |
+
if chunksize == 1:
|
| 402 |
+
result = IMapIterator(self)
|
| 403 |
+
self._taskqueue.put(
|
| 404 |
+
(
|
| 405 |
+
self._guarded_task_generation(result._job, func, iterable),
|
| 406 |
+
result._set_length
|
| 407 |
+
))
|
| 408 |
+
return result
|
| 409 |
+
else:
|
| 410 |
+
if chunksize < 1:
|
| 411 |
+
raise ValueError(
|
| 412 |
+
"Chunksize must be 1+, not {0:n}".format(
|
| 413 |
+
chunksize))
|
| 414 |
+
task_batches = Pool._get_tasks(func, iterable, chunksize)
|
| 415 |
+
result = IMapIterator(self)
|
| 416 |
+
self._taskqueue.put(
|
| 417 |
+
(
|
| 418 |
+
self._guarded_task_generation(result._job,
|
| 419 |
+
mapstar,
|
| 420 |
+
task_batches),
|
| 421 |
+
result._set_length
|
| 422 |
+
))
|
| 423 |
+
return (item for chunk in result for item in chunk)
|
| 424 |
+
|
| 425 |
+
def imap_unordered(self, func, iterable, chunksize=1):
|
| 426 |
+
'''
|
| 427 |
+
Like `imap()` method but ordering of results is arbitrary.
|
| 428 |
+
'''
|
| 429 |
+
self._check_running()
|
| 430 |
+
if chunksize == 1:
|
| 431 |
+
result = IMapUnorderedIterator(self)
|
| 432 |
+
self._taskqueue.put(
|
| 433 |
+
(
|
| 434 |
+
self._guarded_task_generation(result._job, func, iterable),
|
| 435 |
+
result._set_length
|
| 436 |
+
))
|
| 437 |
+
return result
|
| 438 |
+
else:
|
| 439 |
+
if chunksize < 1:
|
| 440 |
+
raise ValueError(
|
| 441 |
+
"Chunksize must be 1+, not {0!r}".format(chunksize))
|
| 442 |
+
task_batches = Pool._get_tasks(func, iterable, chunksize)
|
| 443 |
+
result = IMapUnorderedIterator(self)
|
| 444 |
+
self._taskqueue.put(
|
| 445 |
+
(
|
| 446 |
+
self._guarded_task_generation(result._job,
|
| 447 |
+
mapstar,
|
| 448 |
+
task_batches),
|
| 449 |
+
result._set_length
|
| 450 |
+
))
|
| 451 |
+
return (item for chunk in result for item in chunk)
|
| 452 |
+
|
| 453 |
+
def apply_async(self, func, args=(), kwds={}, callback=None,
|
| 454 |
+
error_callback=None):
|
| 455 |
+
'''
|
| 456 |
+
Asynchronous version of `apply()` method.
|
| 457 |
+
'''
|
| 458 |
+
self._check_running()
|
| 459 |
+
result = ApplyResult(self, callback, error_callback)
|
| 460 |
+
self._taskqueue.put(([(result._job, 0, func, args, kwds)], None))
|
| 461 |
+
return result
|
| 462 |
+
|
| 463 |
+
def map_async(self, func, iterable, chunksize=None, callback=None,
|
| 464 |
+
error_callback=None):
|
| 465 |
+
'''
|
| 466 |
+
Asynchronous version of `map()` method.
|
| 467 |
+
'''
|
| 468 |
+
return self._map_async(func, iterable, mapstar, chunksize, callback,
|
| 469 |
+
error_callback)
|
| 470 |
+
|
| 471 |
+
def _map_async(self, func, iterable, mapper, chunksize=None, callback=None,
|
| 472 |
+
error_callback=None):
|
| 473 |
+
'''
|
| 474 |
+
Helper function to implement map, starmap and their async counterparts.
|
| 475 |
+
'''
|
| 476 |
+
self._check_running()
|
| 477 |
+
if not hasattr(iterable, '__len__'):
|
| 478 |
+
iterable = list(iterable)
|
| 479 |
+
|
| 480 |
+
if chunksize is None:
|
| 481 |
+
chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
|
| 482 |
+
if extra:
|
| 483 |
+
chunksize += 1
|
| 484 |
+
if len(iterable) == 0:
|
| 485 |
+
chunksize = 0
|
| 486 |
+
|
| 487 |
+
task_batches = Pool._get_tasks(func, iterable, chunksize)
|
| 488 |
+
result = MapResult(self, chunksize, len(iterable), callback,
|
| 489 |
+
error_callback=error_callback)
|
| 490 |
+
self._taskqueue.put(
|
| 491 |
+
(
|
| 492 |
+
self._guarded_task_generation(result._job,
|
| 493 |
+
mapper,
|
| 494 |
+
task_batches),
|
| 495 |
+
None
|
| 496 |
+
)
|
| 497 |
+
)
|
| 498 |
+
return result
|
| 499 |
+
|
| 500 |
+
@staticmethod
|
| 501 |
+
def _wait_for_updates(sentinels, change_notifier, timeout=None):
|
| 502 |
+
wait(sentinels, timeout=timeout)
|
| 503 |
+
while not change_notifier.empty():
|
| 504 |
+
change_notifier.get()
|
| 505 |
+
|
| 506 |
+
@classmethod
|
| 507 |
+
def _handle_workers(cls, cache, taskqueue, ctx, Process, processes,
|
| 508 |
+
pool, inqueue, outqueue, initializer, initargs,
|
| 509 |
+
maxtasksperchild, wrap_exception, sentinels,
|
| 510 |
+
change_notifier):
|
| 511 |
+
thread = threading.current_thread()
|
| 512 |
+
|
| 513 |
+
# Keep maintaining workers until the cache gets drained, unless the pool
|
| 514 |
+
# is terminated.
|
| 515 |
+
while thread._state == RUN or (cache and thread._state != TERMINATE):
|
| 516 |
+
cls._maintain_pool(ctx, Process, processes, pool, inqueue,
|
| 517 |
+
outqueue, initializer, initargs,
|
| 518 |
+
maxtasksperchild, wrap_exception)
|
| 519 |
+
|
| 520 |
+
current_sentinels = [*cls._get_worker_sentinels(pool), *sentinels]
|
| 521 |
+
|
| 522 |
+
cls._wait_for_updates(current_sentinels, change_notifier)
|
| 523 |
+
# send sentinel to stop workers
|
| 524 |
+
taskqueue.put(None)
|
| 525 |
+
util.debug('worker handler exiting')
|
| 526 |
+
|
| 527 |
+
@staticmethod
|
| 528 |
+
def _handle_tasks(taskqueue, put, outqueue, pool, cache):
|
| 529 |
+
thread = threading.current_thread()
|
| 530 |
+
|
| 531 |
+
for taskseq, set_length in iter(taskqueue.get, None):
|
| 532 |
+
task = None
|
| 533 |
+
try:
|
| 534 |
+
# iterating taskseq cannot fail
|
| 535 |
+
for task in taskseq:
|
| 536 |
+
if thread._state != RUN:
|
| 537 |
+
util.debug('task handler found thread._state != RUN')
|
| 538 |
+
break
|
| 539 |
+
try:
|
| 540 |
+
put(task)
|
| 541 |
+
except Exception as e:
|
| 542 |
+
job, idx = task[:2]
|
| 543 |
+
try:
|
| 544 |
+
cache[job]._set(idx, (False, e))
|
| 545 |
+
except KeyError:
|
| 546 |
+
pass
|
| 547 |
+
else:
|
| 548 |
+
if set_length:
|
| 549 |
+
util.debug('doing set_length()')
|
| 550 |
+
idx = task[1] if task else -1
|
| 551 |
+
set_length(idx + 1)
|
| 552 |
+
continue
|
| 553 |
+
break
|
| 554 |
+
finally:
|
| 555 |
+
task = taskseq = job = None
|
| 556 |
+
else:
|
| 557 |
+
util.debug('task handler got sentinel')
|
| 558 |
+
|
| 559 |
+
try:
|
| 560 |
+
# tell result handler to finish when cache is empty
|
| 561 |
+
util.debug('task handler sending sentinel to result handler')
|
| 562 |
+
outqueue.put(None)
|
| 563 |
+
|
| 564 |
+
# tell workers there is no more work
|
| 565 |
+
util.debug('task handler sending sentinel to workers')
|
| 566 |
+
for p in pool:
|
| 567 |
+
put(None)
|
| 568 |
+
except OSError:
|
| 569 |
+
util.debug('task handler got OSError when sending sentinels')
|
| 570 |
+
|
| 571 |
+
util.debug('task handler exiting')
|
| 572 |
+
|
| 573 |
+
@staticmethod
|
| 574 |
+
def _handle_results(outqueue, get, cache):
|
| 575 |
+
thread = threading.current_thread()
|
| 576 |
+
|
| 577 |
+
while 1:
|
| 578 |
+
try:
|
| 579 |
+
task = get()
|
| 580 |
+
except (OSError, EOFError):
|
| 581 |
+
util.debug('result handler got EOFError/OSError -- exiting')
|
| 582 |
+
return
|
| 583 |
+
|
| 584 |
+
if thread._state != RUN:
|
| 585 |
+
assert thread._state == TERMINATE, "Thread not in TERMINATE"
|
| 586 |
+
util.debug('result handler found thread._state=TERMINATE')
|
| 587 |
+
break
|
| 588 |
+
|
| 589 |
+
if task is None:
|
| 590 |
+
util.debug('result handler got sentinel')
|
| 591 |
+
break
|
| 592 |
+
|
| 593 |
+
job, i, obj = task
|
| 594 |
+
try:
|
| 595 |
+
cache[job]._set(i, obj)
|
| 596 |
+
except KeyError:
|
| 597 |
+
pass
|
| 598 |
+
task = job = obj = None
|
| 599 |
+
|
| 600 |
+
while cache and thread._state != TERMINATE:
|
| 601 |
+
try:
|
| 602 |
+
task = get()
|
| 603 |
+
except (OSError, EOFError):
|
| 604 |
+
util.debug('result handler got EOFError/OSError -- exiting')
|
| 605 |
+
return
|
| 606 |
+
|
| 607 |
+
if task is None:
|
| 608 |
+
util.debug('result handler ignoring extra sentinel')
|
| 609 |
+
continue
|
| 610 |
+
job, i, obj = task
|
| 611 |
+
try:
|
| 612 |
+
cache[job]._set(i, obj)
|
| 613 |
+
except KeyError:
|
| 614 |
+
pass
|
| 615 |
+
task = job = obj = None
|
| 616 |
+
|
| 617 |
+
if hasattr(outqueue, '_reader'):
|
| 618 |
+
util.debug('ensuring that outqueue is not full')
|
| 619 |
+
# If we don't make room available in outqueue then
|
| 620 |
+
# attempts to add the sentinel (None) to outqueue may
|
| 621 |
+
# block. There is guaranteed to be no more than 2 sentinels.
|
| 622 |
+
try:
|
| 623 |
+
for i in range(10):
|
| 624 |
+
if not outqueue._reader.poll():
|
| 625 |
+
break
|
| 626 |
+
get()
|
| 627 |
+
except (OSError, EOFError):
|
| 628 |
+
pass
|
| 629 |
+
|
| 630 |
+
util.debug('result handler exiting: len(cache)=%s, thread._state=%s',
|
| 631 |
+
len(cache), thread._state)
|
| 632 |
+
|
| 633 |
+
@staticmethod
|
| 634 |
+
def _get_tasks(func, it, size):
|
| 635 |
+
it = iter(it)
|
| 636 |
+
while 1:
|
| 637 |
+
x = tuple(itertools.islice(it, size))
|
| 638 |
+
if not x:
|
| 639 |
+
return
|
| 640 |
+
yield (func, x)
|
| 641 |
+
|
| 642 |
+
def __reduce__(self):
|
| 643 |
+
raise NotImplementedError(
|
| 644 |
+
'pool objects cannot be passed between processes or pickled'
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
def close(self):
|
| 648 |
+
util.debug('closing pool')
|
| 649 |
+
if self._state == RUN:
|
| 650 |
+
self._state = CLOSE
|
| 651 |
+
self._worker_handler._state = CLOSE
|
| 652 |
+
self._change_notifier.put(None)
|
| 653 |
+
|
| 654 |
+
def terminate(self):
|
| 655 |
+
util.debug('terminating pool')
|
| 656 |
+
self._state = TERMINATE
|
| 657 |
+
self._terminate()
|
| 658 |
+
|
| 659 |
+
def join(self):
|
| 660 |
+
util.debug('joining pool')
|
| 661 |
+
if self._state == RUN:
|
| 662 |
+
raise ValueError("Pool is still running")
|
| 663 |
+
elif self._state not in (CLOSE, TERMINATE):
|
| 664 |
+
raise ValueError("In unknown state")
|
| 665 |
+
self._worker_handler.join()
|
| 666 |
+
self._task_handler.join()
|
| 667 |
+
self._result_handler.join()
|
| 668 |
+
for p in self._pool:
|
| 669 |
+
p.join()
|
| 670 |
+
|
| 671 |
+
@staticmethod
|
| 672 |
+
def _help_stuff_finish(inqueue, task_handler, size):
|
| 673 |
+
# task_handler may be blocked trying to put items on inqueue
|
| 674 |
+
util.debug('removing tasks from inqueue until task handler finished')
|
| 675 |
+
inqueue._rlock.acquire()
|
| 676 |
+
while task_handler.is_alive() and inqueue._reader.poll():
|
| 677 |
+
inqueue._reader.recv()
|
| 678 |
+
time.sleep(0)
|
| 679 |
+
|
| 680 |
+
@classmethod
|
| 681 |
+
def _terminate_pool(cls, taskqueue, inqueue, outqueue, pool, change_notifier,
|
| 682 |
+
worker_handler, task_handler, result_handler, cache):
|
| 683 |
+
# this is guaranteed to only be called once
|
| 684 |
+
util.debug('finalizing pool')
|
| 685 |
+
|
| 686 |
+
# Notify that the worker_handler state has been changed so the
|
| 687 |
+
# _handle_workers loop can be unblocked (and exited) in order to
|
| 688 |
+
# send the finalization sentinel all the workers.
|
| 689 |
+
worker_handler._state = TERMINATE
|
| 690 |
+
change_notifier.put(None)
|
| 691 |
+
|
| 692 |
+
task_handler._state = TERMINATE
|
| 693 |
+
|
| 694 |
+
util.debug('helping task handler/workers to finish')
|
| 695 |
+
cls._help_stuff_finish(inqueue, task_handler, len(pool))
|
| 696 |
+
|
| 697 |
+
if (not result_handler.is_alive()) and (len(cache) != 0):
|
| 698 |
+
raise AssertionError(
|
| 699 |
+
"Cannot have cache with result_hander not alive")
|
| 700 |
+
|
| 701 |
+
result_handler._state = TERMINATE
|
| 702 |
+
change_notifier.put(None)
|
| 703 |
+
outqueue.put(None) # sentinel
|
| 704 |
+
|
| 705 |
+
# We must wait for the worker handler to exit before terminating
|
| 706 |
+
# workers because we don't want workers to be restarted behind our back.
|
| 707 |
+
util.debug('joining worker handler')
|
| 708 |
+
if threading.current_thread() is not worker_handler:
|
| 709 |
+
worker_handler.join()
|
| 710 |
+
|
| 711 |
+
# Terminate workers which haven't already finished.
|
| 712 |
+
if pool and hasattr(pool[0], 'terminate'):
|
| 713 |
+
util.debug('terminating workers')
|
| 714 |
+
for p in pool:
|
| 715 |
+
if p.exitcode is None:
|
| 716 |
+
p.terminate()
|
| 717 |
+
|
| 718 |
+
util.debug('joining task handler')
|
| 719 |
+
if threading.current_thread() is not task_handler:
|
| 720 |
+
task_handler.join()
|
| 721 |
+
|
| 722 |
+
util.debug('joining result handler')
|
| 723 |
+
if threading.current_thread() is not result_handler:
|
| 724 |
+
result_handler.join()
|
| 725 |
+
|
| 726 |
+
if pool and hasattr(pool[0], 'terminate'):
|
| 727 |
+
util.debug('joining pool workers')
|
| 728 |
+
for p in pool:
|
| 729 |
+
if p.is_alive():
|
| 730 |
+
# worker has not yet exited
|
| 731 |
+
util.debug('cleaning up worker %d' % p.pid)
|
| 732 |
+
p.join()
|
| 733 |
+
|
| 734 |
+
def __enter__(self):
|
| 735 |
+
self._check_running()
|
| 736 |
+
return self
|
| 737 |
+
|
| 738 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 739 |
+
self.terminate()
|
| 740 |
+
|
| 741 |
+
#
|
| 742 |
+
# Class whose instances are returned by `Pool.apply_async()`
|
| 743 |
+
#
|
| 744 |
+
|
| 745 |
+
class ApplyResult(object):
|
| 746 |
+
|
| 747 |
+
def __init__(self, pool, callback, error_callback):
|
| 748 |
+
self._pool = pool
|
| 749 |
+
self._event = threading.Event()
|
| 750 |
+
self._job = next(job_counter)
|
| 751 |
+
self._cache = pool._cache
|
| 752 |
+
self._callback = callback
|
| 753 |
+
self._error_callback = error_callback
|
| 754 |
+
self._cache[self._job] = self
|
| 755 |
+
|
| 756 |
+
def ready(self):
|
| 757 |
+
return self._event.is_set()
|
| 758 |
+
|
| 759 |
+
def successful(self):
|
| 760 |
+
if not self.ready():
|
| 761 |
+
raise ValueError("{0!r} not ready".format(self))
|
| 762 |
+
return self._success
|
| 763 |
+
|
| 764 |
+
def wait(self, timeout=None):
|
| 765 |
+
self._event.wait(timeout)
|
| 766 |
+
|
| 767 |
+
def get(self, timeout=None):
|
| 768 |
+
self.wait(timeout)
|
| 769 |
+
if not self.ready():
|
| 770 |
+
raise TimeoutError
|
| 771 |
+
if self._success:
|
| 772 |
+
return self._value
|
| 773 |
+
else:
|
| 774 |
+
raise self._value
|
| 775 |
+
|
| 776 |
+
def _set(self, i, obj):
|
| 777 |
+
self._success, self._value = obj
|
| 778 |
+
if self._callback and self._success:
|
| 779 |
+
self._callback(self._value)
|
| 780 |
+
if self._error_callback and not self._success:
|
| 781 |
+
self._error_callback(self._value)
|
| 782 |
+
self._event.set()
|
| 783 |
+
del self._cache[self._job]
|
| 784 |
+
self._pool = None
|
| 785 |
+
|
| 786 |
+
__class_getitem__ = classmethod(types.GenericAlias)
|
| 787 |
+
|
| 788 |
+
AsyncResult = ApplyResult # create alias -- see #17805
|
| 789 |
+
|
| 790 |
+
#
|
| 791 |
+
# Class whose instances are returned by `Pool.map_async()`
|
| 792 |
+
#
|
| 793 |
+
|
| 794 |
+
class MapResult(ApplyResult):
|
| 795 |
+
|
| 796 |
+
def __init__(self, pool, chunksize, length, callback, error_callback):
|
| 797 |
+
ApplyResult.__init__(self, pool, callback,
|
| 798 |
+
error_callback=error_callback)
|
| 799 |
+
self._success = True
|
| 800 |
+
self._value = [None] * length
|
| 801 |
+
self._chunksize = chunksize
|
| 802 |
+
if chunksize <= 0:
|
| 803 |
+
self._number_left = 0
|
| 804 |
+
self._event.set()
|
| 805 |
+
del self._cache[self._job]
|
| 806 |
+
else:
|
| 807 |
+
self._number_left = length//chunksize + bool(length % chunksize)
|
| 808 |
+
|
| 809 |
+
def _set(self, i, success_result):
|
| 810 |
+
self._number_left -= 1
|
| 811 |
+
success, result = success_result
|
| 812 |
+
if success and self._success:
|
| 813 |
+
self._value[i*self._chunksize:(i+1)*self._chunksize] = result
|
| 814 |
+
if self._number_left == 0:
|
| 815 |
+
if self._callback:
|
| 816 |
+
self._callback(self._value)
|
| 817 |
+
del self._cache[self._job]
|
| 818 |
+
self._event.set()
|
| 819 |
+
self._pool = None
|
| 820 |
+
else:
|
| 821 |
+
if not success and self._success:
|
| 822 |
+
# only store first exception
|
| 823 |
+
self._success = False
|
| 824 |
+
self._value = result
|
| 825 |
+
if self._number_left == 0:
|
| 826 |
+
# only consider the result ready once all jobs are done
|
| 827 |
+
if self._error_callback:
|
| 828 |
+
self._error_callback(self._value)
|
| 829 |
+
del self._cache[self._job]
|
| 830 |
+
self._event.set()
|
| 831 |
+
self._pool = None
|
| 832 |
+
|
| 833 |
+
#
|
| 834 |
+
# Class whose instances are returned by `Pool.imap()`
|
| 835 |
+
#
|
| 836 |
+
|
| 837 |
+
class IMapIterator(object):
|
| 838 |
+
|
| 839 |
+
def __init__(self, pool):
|
| 840 |
+
self._pool = pool
|
| 841 |
+
self._cond = threading.Condition(threading.Lock())
|
| 842 |
+
self._job = next(job_counter)
|
| 843 |
+
self._cache = pool._cache
|
| 844 |
+
self._items = collections.deque()
|
| 845 |
+
self._index = 0
|
| 846 |
+
self._length = None
|
| 847 |
+
self._unsorted = {}
|
| 848 |
+
self._cache[self._job] = self
|
| 849 |
+
|
| 850 |
+
def __iter__(self):
|
| 851 |
+
return self
|
| 852 |
+
|
| 853 |
+
def next(self, timeout=None):
|
| 854 |
+
with self._cond:
|
| 855 |
+
try:
|
| 856 |
+
item = self._items.popleft()
|
| 857 |
+
except IndexError:
|
| 858 |
+
if self._index == self._length:
|
| 859 |
+
self._pool = None
|
| 860 |
+
raise StopIteration from None
|
| 861 |
+
self._cond.wait(timeout)
|
| 862 |
+
try:
|
| 863 |
+
item = self._items.popleft()
|
| 864 |
+
except IndexError:
|
| 865 |
+
if self._index == self._length:
|
| 866 |
+
self._pool = None
|
| 867 |
+
raise StopIteration from None
|
| 868 |
+
raise TimeoutError from None
|
| 869 |
+
|
| 870 |
+
success, value = item
|
| 871 |
+
if success:
|
| 872 |
+
return value
|
| 873 |
+
raise value
|
| 874 |
+
|
| 875 |
+
__next__ = next # XXX
|
| 876 |
+
|
| 877 |
+
def _set(self, i, obj):
|
| 878 |
+
with self._cond:
|
| 879 |
+
if self._index == i:
|
| 880 |
+
self._items.append(obj)
|
| 881 |
+
self._index += 1
|
| 882 |
+
while self._index in self._unsorted:
|
| 883 |
+
obj = self._unsorted.pop(self._index)
|
| 884 |
+
self._items.append(obj)
|
| 885 |
+
self._index += 1
|
| 886 |
+
self._cond.notify()
|
| 887 |
+
else:
|
| 888 |
+
self._unsorted[i] = obj
|
| 889 |
+
|
| 890 |
+
if self._index == self._length:
|
| 891 |
+
del self._cache[self._job]
|
| 892 |
+
self._pool = None
|
| 893 |
+
|
| 894 |
+
def _set_length(self, length):
|
| 895 |
+
with self._cond:
|
| 896 |
+
self._length = length
|
| 897 |
+
if self._index == self._length:
|
| 898 |
+
self._cond.notify()
|
| 899 |
+
del self._cache[self._job]
|
| 900 |
+
self._pool = None
|
| 901 |
+
|
| 902 |
+
#
|
| 903 |
+
# Class whose instances are returned by `Pool.imap_unordered()`
|
| 904 |
+
#
|
| 905 |
+
|
| 906 |
+
class IMapUnorderedIterator(IMapIterator):
|
| 907 |
+
|
| 908 |
+
def _set(self, i, obj):
|
| 909 |
+
with self._cond:
|
| 910 |
+
self._items.append(obj)
|
| 911 |
+
self._index += 1
|
| 912 |
+
self._cond.notify()
|
| 913 |
+
if self._index == self._length:
|
| 914 |
+
del self._cache[self._job]
|
| 915 |
+
self._pool = None
|
| 916 |
+
|
| 917 |
+
#
|
| 918 |
+
#
|
| 919 |
+
#
|
| 920 |
+
|
| 921 |
+
class ThreadPool(Pool):
|
| 922 |
+
_wrap_exception = False
|
| 923 |
+
|
| 924 |
+
@staticmethod
|
| 925 |
+
def Process(ctx, *args, **kwds):
|
| 926 |
+
from .dummy import Process
|
| 927 |
+
return Process(*args, **kwds)
|
| 928 |
+
|
| 929 |
+
def __init__(self, processes=None, initializer=None, initargs=()):
|
| 930 |
+
Pool.__init__(self, processes, initializer, initargs)
|
| 931 |
+
|
| 932 |
+
def _setup_queues(self):
|
| 933 |
+
self._inqueue = queue.SimpleQueue()
|
| 934 |
+
self._outqueue = queue.SimpleQueue()
|
| 935 |
+
self._quick_put = self._inqueue.put
|
| 936 |
+
self._quick_get = self._outqueue.get
|
| 937 |
+
|
| 938 |
+
def _get_sentinels(self):
|
| 939 |
+
return [self._change_notifier._reader]
|
| 940 |
+
|
| 941 |
+
@staticmethod
|
| 942 |
+
def _get_worker_sentinels(workers):
|
| 943 |
+
return []
|
| 944 |
+
|
| 945 |
+
@staticmethod
|
| 946 |
+
def _help_stuff_finish(inqueue, task_handler, size):
|
| 947 |
+
# drain inqueue, and put sentinels at its head to make workers finish
|
| 948 |
+
try:
|
| 949 |
+
while True:
|
| 950 |
+
inqueue.get(block=False)
|
| 951 |
+
except queue.Empty:
|
| 952 |
+
pass
|
| 953 |
+
for i in range(size):
|
| 954 |
+
inqueue.put(None)
|
| 955 |
+
|
| 956 |
+
def _wait_for_updates(self, sentinels, change_notifier, timeout):
|
| 957 |
+
time.sleep(timeout)
|