ZTWHHH commited on
Commit
788fdea
·
verified ·
1 Parent(s): 60dbcc8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. parrot/lib/python3.10/importlib/__pycache__/machinery.cpython-310.pyc +0 -0
  2. parrot/lib/python3.10/importlib/__pycache__/readers.cpython-310.pyc +0 -0
  3. parrot/lib/python3.10/importlib/_adapters.py +83 -0
  4. parrot/lib/python3.10/importlib/_bootstrap_external.py +1686 -0
  5. parrot/lib/python3.10/importlib/util.py +302 -0
  6. parrot/lib/python3.10/logging/__pycache__/config.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/logging/config.py +947 -0
  8. parrot/lib/python3.10/logging/handlers.py +1587 -0
  9. parrot/lib/python3.10/turtledemo/__init__.py +14 -0
  10. parrot/lib/python3.10/turtledemo/__main__.py +398 -0
  11. parrot/lib/python3.10/turtledemo/__pycache__/__main__.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/turtledemo/__pycache__/bytedesign.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/turtledemo/__pycache__/chaos.cpython-310.pyc +0 -0
  14. parrot/lib/python3.10/turtledemo/__pycache__/clock.cpython-310.pyc +0 -0
  15. parrot/lib/python3.10/turtledemo/__pycache__/colormixer.cpython-310.pyc +0 -0
  16. parrot/lib/python3.10/turtledemo/__pycache__/forest.cpython-310.pyc +0 -0
  17. parrot/lib/python3.10/turtledemo/__pycache__/fractalcurves.cpython-310.pyc +0 -0
  18. parrot/lib/python3.10/turtledemo/__pycache__/lindenmayer.cpython-310.pyc +0 -0
  19. parrot/lib/python3.10/turtledemo/__pycache__/minimal_hanoi.cpython-310.pyc +0 -0
  20. parrot/lib/python3.10/turtledemo/__pycache__/nim.cpython-310.pyc +0 -0
  21. parrot/lib/python3.10/turtledemo/__pycache__/paint.cpython-310.pyc +0 -0
  22. parrot/lib/python3.10/turtledemo/__pycache__/peace.cpython-310.pyc +0 -0
  23. parrot/lib/python3.10/turtledemo/__pycache__/planet_and_moon.cpython-310.pyc +0 -0
  24. parrot/lib/python3.10/turtledemo/__pycache__/rosette.cpython-310.pyc +0 -0
  25. parrot/lib/python3.10/turtledemo/__pycache__/round_dance.cpython-310.pyc +0 -0
  26. parrot/lib/python3.10/turtledemo/__pycache__/sorting_animate.cpython-310.pyc +0 -0
  27. parrot/lib/python3.10/turtledemo/__pycache__/tree.cpython-310.pyc +0 -0
  28. parrot/lib/python3.10/turtledemo/__pycache__/two_canvases.cpython-310.pyc +0 -0
  29. parrot/lib/python3.10/turtledemo/__pycache__/yinyang.cpython-310.pyc +0 -0
  30. parrot/lib/python3.10/turtledemo/bytedesign.py +161 -0
  31. parrot/lib/python3.10/turtledemo/chaos.py +59 -0
  32. parrot/lib/python3.10/turtledemo/clock.py +131 -0
  33. parrot/lib/python3.10/turtledemo/colormixer.py +58 -0
  34. parrot/lib/python3.10/turtledemo/forest.py +108 -0
  35. parrot/lib/python3.10/turtledemo/fractalcurves.py +138 -0
  36. parrot/lib/python3.10/turtledemo/lindenmayer.py +119 -0
  37. parrot/lib/python3.10/turtledemo/minimal_hanoi.py +79 -0
  38. parrot/lib/python3.10/turtledemo/nim.py +226 -0
  39. parrot/lib/python3.10/turtledemo/paint.py +54 -0
  40. parrot/lib/python3.10/turtledemo/peace.py +61 -0
  41. parrot/lib/python3.10/turtledemo/penrose.py +175 -0
  42. parrot/lib/python3.10/turtledemo/planet_and_moon.py +111 -0
  43. parrot/lib/python3.10/turtledemo/rosette.py +65 -0
  44. parrot/lib/python3.10/turtledemo/round_dance.py +86 -0
  45. parrot/lib/python3.10/turtledemo/sorting_animate.py +204 -0
  46. parrot/lib/python3.10/turtledemo/tree.py +62 -0
  47. parrot/lib/python3.10/turtledemo/turtle.cfg +10 -0
  48. parrot/lib/python3.10/turtledemo/two_canvases.py +54 -0
  49. parrot/lib/python3.10/turtledemo/yinyang.py +49 -0
  50. parrot/lib/python3.10/xml/__pycache__/__init__.cpython-310.pyc +0 -0
parrot/lib/python3.10/importlib/__pycache__/machinery.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
parrot/lib/python3.10/importlib/__pycache__/readers.cpython-310.pyc ADDED
Binary file (5.18 kB). View file
 
parrot/lib/python3.10/importlib/_adapters.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import suppress
2
+
3
+ from . import abc
4
+
5
+
6
+ class SpecLoaderAdapter:
7
+ """
8
+ Adapt a package spec to adapt the underlying loader.
9
+ """
10
+
11
+ def __init__(self, spec, adapter=lambda spec: spec.loader):
12
+ self.spec = spec
13
+ self.loader = adapter(spec)
14
+
15
+ def __getattr__(self, name):
16
+ return getattr(self.spec, name)
17
+
18
+
19
+ class TraversableResourcesLoader:
20
+ """
21
+ Adapt a loader to provide TraversableResources.
22
+ """
23
+
24
+ def __init__(self, spec):
25
+ self.spec = spec
26
+
27
+ def get_resource_reader(self, name):
28
+ return DegenerateFiles(self.spec)._native()
29
+
30
+
31
+ class DegenerateFiles:
32
+ """
33
+ Adapter for an existing or non-existant resource reader
34
+ to provide a degenerate .files().
35
+ """
36
+
37
+ class Path(abc.Traversable):
38
+ def iterdir(self):
39
+ return iter(())
40
+
41
+ def is_dir(self):
42
+ return False
43
+
44
+ is_file = exists = is_dir # type: ignore
45
+
46
+ def joinpath(self, other):
47
+ return DegenerateFiles.Path()
48
+
49
+ @property
50
+ def name(self):
51
+ return ''
52
+
53
+ def open(self, mode='rb', *args, **kwargs):
54
+ raise ValueError()
55
+
56
+ def __init__(self, spec):
57
+ self.spec = spec
58
+
59
+ @property
60
+ def _reader(self):
61
+ with suppress(AttributeError):
62
+ return self.spec.loader.get_resource_reader(self.spec.name)
63
+
64
+ def _native(self):
65
+ """
66
+ Return the native reader if it supports files().
67
+ """
68
+ reader = self._reader
69
+ return reader if hasattr(reader, 'files') else self
70
+
71
+ def __getattr__(self, attr):
72
+ return getattr(self._reader, attr)
73
+
74
+ def files(self):
75
+ return DegenerateFiles.Path()
76
+
77
+
78
+ def wrap_spec(package):
79
+ """
80
+ Construct a package spec with traversable compatibility
81
+ on the spec/loader/reader.
82
+ """
83
+ return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)
parrot/lib/python3.10/importlib/_bootstrap_external.py ADDED
@@ -0,0 +1,1686 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core implementation of path-based import.
2
+
3
+ This module is NOT meant to be directly imported! It has been designed such
4
+ that it can be bootstrapped into Python as the implementation of import. As
5
+ such it requires the injection of specific modules and attributes in order to
6
+ work. One should use importlib as the public-facing version of this module.
7
+
8
+ """
9
+ # IMPORTANT: Whenever making changes to this module, be sure to run a top-level
10
+ # `make regen-importlib` followed by `make` in order to get the frozen version
11
+ # of the module updated. Not doing so will result in the Makefile to fail for
12
+ # all others who don't have a ./python around to freeze the module in the early
13
+ # stages of compilation.
14
+ #
15
+
16
+ # See importlib._setup() for what is injected into the global namespace.
17
+
18
+ # When editing this code be aware that code executed at import time CANNOT
19
+ # reference any injected objects! This includes not only global code but also
20
+ # anything specified at the class level.
21
+
22
+ # Module injected manually by _set_bootstrap_module()
23
+ _bootstrap = None
24
+
25
+ # Import builtin modules
26
+ import _imp
27
+ import _io
28
+ import sys
29
+ import _warnings
30
+ import marshal
31
+
32
+
33
+ _MS_WINDOWS = (sys.platform == 'win32')
34
+ if _MS_WINDOWS:
35
+ import nt as _os
36
+ import winreg
37
+ else:
38
+ import posix as _os
39
+
40
+
41
+ if _MS_WINDOWS:
42
+ path_separators = ['\\', '/']
43
+ else:
44
+ path_separators = ['/']
45
+ # Assumption made in _path_join()
46
+ assert all(len(sep) == 1 for sep in path_separators)
47
+ path_sep = path_separators[0]
48
+ path_sep_tuple = tuple(path_separators)
49
+ path_separators = ''.join(path_separators)
50
+ _pathseps_with_colon = {f':{s}' for s in path_separators}
51
+
52
+
53
+ # Bootstrap-related code ######################################################
54
+ _CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
55
+ _CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin'
56
+ _CASE_INSENSITIVE_PLATFORMS = (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
57
+ + _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
58
+
59
+
60
+ def _make_relax_case():
61
+ if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
62
+ if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):
63
+ key = 'PYTHONCASEOK'
64
+ else:
65
+ key = b'PYTHONCASEOK'
66
+
67
+ def _relax_case():
68
+ """True if filenames must be checked case-insensitively and ignore environment flags are not set."""
69
+ return not sys.flags.ignore_environment and key in _os.environ
70
+ else:
71
+ def _relax_case():
72
+ """True if filenames must be checked case-insensitively."""
73
+ return False
74
+ return _relax_case
75
+
76
+ _relax_case = _make_relax_case()
77
+
78
+
79
+ def _pack_uint32(x):
80
+ """Convert a 32-bit integer to little-endian."""
81
+ return (int(x) & 0xFFFFFFFF).to_bytes(4, 'little')
82
+
83
+
84
+ def _unpack_uint32(data):
85
+ """Convert 4 bytes in little-endian to an integer."""
86
+ assert len(data) == 4
87
+ return int.from_bytes(data, 'little')
88
+
89
+ def _unpack_uint16(data):
90
+ """Convert 2 bytes in little-endian to an integer."""
91
+ assert len(data) == 2
92
+ return int.from_bytes(data, 'little')
93
+
94
+
95
+ if _MS_WINDOWS:
96
+ def _path_join(*path_parts):
97
+ """Replacement for os.path.join()."""
98
+ if not path_parts:
99
+ return ""
100
+ if len(path_parts) == 1:
101
+ return path_parts[0]
102
+ root = ""
103
+ path = []
104
+ for new_root, tail in map(_os._path_splitroot, path_parts):
105
+ if new_root.startswith(path_sep_tuple) or new_root.endswith(path_sep_tuple):
106
+ root = new_root.rstrip(path_separators) or root
107
+ path = [path_sep + tail]
108
+ elif new_root.endswith(':'):
109
+ if root.casefold() != new_root.casefold():
110
+ # Drive relative paths have to be resolved by the OS, so we reset the
111
+ # tail but do not add a path_sep prefix.
112
+ root = new_root
113
+ path = [tail]
114
+ else:
115
+ path.append(tail)
116
+ else:
117
+ root = new_root or root
118
+ path.append(tail)
119
+ path = [p.rstrip(path_separators) for p in path if p]
120
+ if len(path) == 1 and not path[0]:
121
+ # Avoid losing the root's trailing separator when joining with nothing
122
+ return root + path_sep
123
+ return root + path_sep.join(path)
124
+
125
+ else:
126
+ def _path_join(*path_parts):
127
+ """Replacement for os.path.join()."""
128
+ return path_sep.join([part.rstrip(path_separators)
129
+ for part in path_parts if part])
130
+
131
+
132
+ def _path_split(path):
133
+ """Replacement for os.path.split()."""
134
+ i = max(path.rfind(p) for p in path_separators)
135
+ if i < 0:
136
+ return '', path
137
+ return path[:i], path[i + 1:]
138
+
139
+
140
+ def _path_stat(path):
141
+ """Stat the path.
142
+
143
+ Made a separate function to make it easier to override in experiments
144
+ (e.g. cache stat results).
145
+
146
+ """
147
+ return _os.stat(path)
148
+
149
+
150
+ def _path_is_mode_type(path, mode):
151
+ """Test whether the path is the specified mode type."""
152
+ try:
153
+ stat_info = _path_stat(path)
154
+ except OSError:
155
+ return False
156
+ return (stat_info.st_mode & 0o170000) == mode
157
+
158
+
159
+ def _path_isfile(path):
160
+ """Replacement for os.path.isfile."""
161
+ return _path_is_mode_type(path, 0o100000)
162
+
163
+
164
+ def _path_isdir(path):
165
+ """Replacement for os.path.isdir."""
166
+ if not path:
167
+ path = _os.getcwd()
168
+ return _path_is_mode_type(path, 0o040000)
169
+
170
+
171
+ if _MS_WINDOWS:
172
+ def _path_isabs(path):
173
+ """Replacement for os.path.isabs."""
174
+ if not path:
175
+ return False
176
+ root = _os._path_splitroot(path)[0].replace('/', '\\')
177
+ return len(root) > 1 and (root.startswith('\\\\') or root.endswith('\\'))
178
+
179
+ else:
180
+ def _path_isabs(path):
181
+ """Replacement for os.path.isabs."""
182
+ return path.startswith(path_separators)
183
+
184
+
185
+ def _write_atomic(path, data, mode=0o666):
186
+ """Best-effort function to write data to a path atomically.
187
+ Be prepared to handle a FileExistsError if concurrent writing of the
188
+ temporary file is attempted."""
189
+ # id() is used to generate a pseudo-random filename.
190
+ path_tmp = '{}.{}'.format(path, id(path))
191
+ fd = _os.open(path_tmp,
192
+ _os.O_EXCL | _os.O_CREAT | _os.O_WRONLY, mode & 0o666)
193
+ try:
194
+ # We first write data to a temporary file, and then use os.replace() to
195
+ # perform an atomic rename.
196
+ with _io.FileIO(fd, 'wb') as file:
197
+ file.write(data)
198
+ _os.replace(path_tmp, path)
199
+ except OSError:
200
+ try:
201
+ _os.unlink(path_tmp)
202
+ except OSError:
203
+ pass
204
+ raise
205
+
206
+
207
+ _code_type = type(_write_atomic.__code__)
208
+
209
+
210
+ # Finder/loader utility code ###############################################
211
+
212
+ # Magic word to reject .pyc files generated by other Python versions.
213
+ # It should change for each incompatible change to the bytecode.
214
+ #
215
+ # The value of CR and LF is incorporated so if you ever read or write
216
+ # a .pyc file in text mode the magic number will be wrong; also, the
217
+ # Apple MPW compiler swaps their values, botching string constants.
218
+ #
219
+ # There were a variety of old schemes for setting the magic number.
220
+ # The current working scheme is to increment the previous value by
221
+ # 10.
222
+ #
223
+ # Starting with the adoption of PEP 3147 in Python 3.2, every bump in magic
224
+ # number also includes a new "magic tag", i.e. a human readable string used
225
+ # to represent the magic number in __pycache__ directories. When you change
226
+ # the magic number, you must also set a new unique magic tag. Generally this
227
+ # can be named after the Python major version of the magic number bump, but
228
+ # it can really be anything, as long as it's different than anything else
229
+ # that's come before. The tags are included in the following table, starting
230
+ # with Python 3.2a0.
231
+ #
232
+ # Known values:
233
+ # Python 1.5: 20121
234
+ # Python 1.5.1: 20121
235
+ # Python 1.5.2: 20121
236
+ # Python 1.6: 50428
237
+ # Python 2.0: 50823
238
+ # Python 2.0.1: 50823
239
+ # Python 2.1: 60202
240
+ # Python 2.1.1: 60202
241
+ # Python 2.1.2: 60202
242
+ # Python 2.2: 60717
243
+ # Python 2.3a0: 62011
244
+ # Python 2.3a0: 62021
245
+ # Python 2.3a0: 62011 (!)
246
+ # Python 2.4a0: 62041
247
+ # Python 2.4a3: 62051
248
+ # Python 2.4b1: 62061
249
+ # Python 2.5a0: 62071
250
+ # Python 2.5a0: 62081 (ast-branch)
251
+ # Python 2.5a0: 62091 (with)
252
+ # Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
253
+ # Python 2.5b3: 62101 (fix wrong code: for x, in ...)
254
+ # Python 2.5b3: 62111 (fix wrong code: x += yield)
255
+ # Python 2.5c1: 62121 (fix wrong lnotab with for loops and
256
+ # storing constants that should have been removed)
257
+ # Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
258
+ # Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
259
+ # Python 2.6a1: 62161 (WITH_CLEANUP optimization)
260
+ # Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
261
+ # Python 2.7a0: 62181 (optimize conditional branches:
262
+ # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
263
+ # Python 2.7a0 62191 (introduce SETUP_WITH)
264
+ # Python 2.7a0 62201 (introduce BUILD_SET)
265
+ # Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
266
+ # Python 3000: 3000
267
+ # 3010 (removed UNARY_CONVERT)
268
+ # 3020 (added BUILD_SET)
269
+ # 3030 (added keyword-only parameters)
270
+ # 3040 (added signature annotations)
271
+ # 3050 (print becomes a function)
272
+ # 3060 (PEP 3115 metaclass syntax)
273
+ # 3061 (string literals become unicode)
274
+ # 3071 (PEP 3109 raise changes)
275
+ # 3081 (PEP 3137 make __file__ and __name__ unicode)
276
+ # 3091 (kill str8 interning)
277
+ # 3101 (merge from 2.6a0, see 62151)
278
+ # 3103 (__file__ points to source file)
279
+ # Python 3.0a4: 3111 (WITH_CLEANUP optimization).
280
+ # Python 3.0b1: 3131 (lexical exception stacking, including POP_EXCEPT
281
+ #3021)
282
+ # Python 3.1a1: 3141 (optimize list, set and dict comprehensions:
283
+ # change LIST_APPEND and SET_ADD, add MAP_ADD #2183)
284
+ # Python 3.1a1: 3151 (optimize conditional branches:
285
+ # introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE
286
+ #4715)
287
+ # Python 3.2a1: 3160 (add SETUP_WITH #6101)
288
+ # tag: cpython-32
289
+ # Python 3.2a2: 3170 (add DUP_TOP_TWO, remove DUP_TOPX and ROT_FOUR #9225)
290
+ # tag: cpython-32
291
+ # Python 3.2a3 3180 (add DELETE_DEREF #4617)
292
+ # Python 3.3a1 3190 (__class__ super closure changed)
293
+ # Python 3.3a1 3200 (PEP 3155 __qualname__ added #13448)
294
+ # Python 3.3a1 3210 (added size modulo 2**32 to the pyc header #13645)
295
+ # Python 3.3a2 3220 (changed PEP 380 implementation #14230)
296
+ # Python 3.3a4 3230 (revert changes to implicit __class__ closure #14857)
297
+ # Python 3.4a1 3250 (evaluate positional default arguments before
298
+ # keyword-only defaults #16967)
299
+ # Python 3.4a1 3260 (add LOAD_CLASSDEREF; allow locals of class to override
300
+ # free vars #17853)
301
+ # Python 3.4a1 3270 (various tweaks to the __class__ closure #12370)
302
+ # Python 3.4a1 3280 (remove implicit class argument)
303
+ # Python 3.4a4 3290 (changes to __qualname__ computation #19301)
304
+ # Python 3.4a4 3300 (more changes to __qualname__ computation #19301)
305
+ # Python 3.4rc2 3310 (alter __qualname__ computation #20625)
306
+ # Python 3.5a1 3320 (PEP 465: Matrix multiplication operator #21176)
307
+ # Python 3.5b1 3330 (PEP 448: Additional Unpacking Generalizations #2292)
308
+ # Python 3.5b2 3340 (fix dictionary display evaluation order #11205)
309
+ # Python 3.5b3 3350 (add GET_YIELD_FROM_ITER opcode #24400)
310
+ # Python 3.5.2 3351 (fix BUILD_MAP_UNPACK_WITH_CALL opcode #27286)
311
+ # Python 3.6a0 3360 (add FORMAT_VALUE opcode #25483)
312
+ # Python 3.6a1 3361 (lineno delta of code.co_lnotab becomes signed #26107)
313
+ # Python 3.6a2 3370 (16 bit wordcode #26647)
314
+ # Python 3.6a2 3371 (add BUILD_CONST_KEY_MAP opcode #27140)
315
+ # Python 3.6a2 3372 (MAKE_FUNCTION simplification, remove MAKE_CLOSURE
316
+ # #27095)
317
+ # Python 3.6b1 3373 (add BUILD_STRING opcode #27078)
318
+ # Python 3.6b1 3375 (add SETUP_ANNOTATIONS and STORE_ANNOTATION opcodes
319
+ # #27985)
320
+ # Python 3.6b1 3376 (simplify CALL_FUNCTIONs & BUILD_MAP_UNPACK_WITH_CALL
321
+ #27213)
322
+ # Python 3.6b1 3377 (set __class__ cell from type.__new__ #23722)
323
+ # Python 3.6b2 3378 (add BUILD_TUPLE_UNPACK_WITH_CALL #28257)
324
+ # Python 3.6rc1 3379 (more thorough __class__ validation #23722)
325
+ # Python 3.7a1 3390 (add LOAD_METHOD and CALL_METHOD opcodes #26110)
326
+ # Python 3.7a2 3391 (update GET_AITER #31709)
327
+ # Python 3.7a4 3392 (PEP 552: Deterministic pycs #31650)
328
+ # Python 3.7b1 3393 (remove STORE_ANNOTATION opcode #32550)
329
+ # Python 3.7b5 3394 (restored docstring as the first stmt in the body;
330
+ # this might affected the first line number #32911)
331
+ # Python 3.8a1 3400 (move frame block handling to compiler #17611)
332
+ # Python 3.8a1 3401 (add END_ASYNC_FOR #33041)
333
+ # Python 3.8a1 3410 (PEP570 Python Positional-Only Parameters #36540)
334
+ # Python 3.8b2 3411 (Reverse evaluation order of key: value in dict
335
+ # comprehensions #35224)
336
+ # Python 3.8b2 3412 (Swap the position of positional args and positional
337
+ # only args in ast.arguments #37593)
338
+ # Python 3.8b4 3413 (Fix "break" and "continue" in "finally" #37830)
339
+ # Python 3.9a0 3420 (add LOAD_ASSERTION_ERROR #34880)
340
+ # Python 3.9a0 3421 (simplified bytecode for with blocks #32949)
341
+ # Python 3.9a0 3422 (remove BEGIN_FINALLY, END_FINALLY, CALL_FINALLY, POP_FINALLY bytecodes #33387)
342
+ # Python 3.9a2 3423 (add IS_OP, CONTAINS_OP and JUMP_IF_NOT_EXC_MATCH bytecodes #39156)
343
+ # Python 3.9a2 3424 (simplify bytecodes for *value unpacking)
344
+ # Python 3.9a2 3425 (simplify bytecodes for **value unpacking)
345
+ # Python 3.10a1 3430 (Make 'annotations' future by default)
346
+ # Python 3.10a1 3431 (New line number table format -- PEP 626)
347
+ # Python 3.10a2 3432 (Function annotation for MAKE_FUNCTION is changed from dict to tuple bpo-42202)
348
+ # Python 3.10a2 3433 (RERAISE restores f_lasti if oparg != 0)
349
+ # Python 3.10a6 3434 (PEP 634: Structural Pattern Matching)
350
+ # Python 3.10a7 3435 Use instruction offsets (as opposed to byte offsets).
351
+ # Python 3.10b1 3436 (Add GEN_START bytecode #43683)
352
+ # Python 3.10b1 3437 (Undo making 'annotations' future by default - We like to dance among core devs!)
353
+ # Python 3.10b1 3438 Safer line number table handling.
354
+ # Python 3.10b1 3439 (Add ROT_N)
355
+
356
+ #
357
+ # MAGIC must change whenever the bytecode emitted by the compiler may no
358
+ # longer be understood by older implementations of the eval loop (usually
359
+ # due to the addition of new opcodes).
360
+ #
361
+ # Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array
362
+ # in PC/launcher.c must also be updated.
363
+
364
+ MAGIC_NUMBER = (3439).to_bytes(2, 'little') + b'\r\n'
365
+ _RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little') # For import.c
366
+
367
+ _PYCACHE = '__pycache__'
368
+ _OPT = 'opt-'
369
+
370
+ SOURCE_SUFFIXES = ['.py']
371
+ if _MS_WINDOWS:
372
+ SOURCE_SUFFIXES.append('.pyw')
373
+
374
+ EXTENSION_SUFFIXES = _imp.extension_suffixes()
375
+
376
+ BYTECODE_SUFFIXES = ['.pyc']
377
+ # Deprecated.
378
+ DEBUG_BYTECODE_SUFFIXES = OPTIMIZED_BYTECODE_SUFFIXES = BYTECODE_SUFFIXES
379
+
380
+ def cache_from_source(path, debug_override=None, *, optimization=None):
381
+ """Given the path to a .py file, return the path to its .pyc file.
382
+
383
+ The .py file does not need to exist; this simply returns the path to the
384
+ .pyc file calculated as if the .py file were imported.
385
+
386
+ The 'optimization' parameter controls the presumed optimization level of
387
+ the bytecode file. If 'optimization' is not None, the string representation
388
+ of the argument is taken and verified to be alphanumeric (else ValueError
389
+ is raised).
390
+
391
+ The debug_override parameter is deprecated. If debug_override is not None,
392
+ a True value is the same as setting 'optimization' to the empty string
393
+ while a False value is equivalent to setting 'optimization' to '1'.
394
+
395
+ If sys.implementation.cache_tag is None then NotImplementedError is raised.
396
+
397
+ """
398
+ if debug_override is not None:
399
+ _warnings.warn('the debug_override parameter is deprecated; use '
400
+ "'optimization' instead", DeprecationWarning)
401
+ if optimization is not None:
402
+ message = 'debug_override or optimization must be set to None'
403
+ raise TypeError(message)
404
+ optimization = '' if debug_override else 1
405
+ path = _os.fspath(path)
406
+ head, tail = _path_split(path)
407
+ base, sep, rest = tail.rpartition('.')
408
+ tag = sys.implementation.cache_tag
409
+ if tag is None:
410
+ raise NotImplementedError('sys.implementation.cache_tag is None')
411
+ almost_filename = ''.join([(base if base else rest), sep, tag])
412
+ if optimization is None:
413
+ if sys.flags.optimize == 0:
414
+ optimization = ''
415
+ else:
416
+ optimization = sys.flags.optimize
417
+ optimization = str(optimization)
418
+ if optimization != '':
419
+ if not optimization.isalnum():
420
+ raise ValueError('{!r} is not alphanumeric'.format(optimization))
421
+ almost_filename = '{}.{}{}'.format(almost_filename, _OPT, optimization)
422
+ filename = almost_filename + BYTECODE_SUFFIXES[0]
423
+ if sys.pycache_prefix is not None:
424
+ # We need an absolute path to the py file to avoid the possibility of
425
+ # collisions within sys.pycache_prefix, if someone has two different
426
+ # `foo/bar.py` on their system and they import both of them using the
427
+ # same sys.pycache_prefix. Let's say sys.pycache_prefix is
428
+ # `C:\Bytecode`; the idea here is that if we get `Foo\Bar`, we first
429
+ # make it absolute (`C:\Somewhere\Foo\Bar`), then make it root-relative
430
+ # (`Somewhere\Foo\Bar`), so we end up placing the bytecode file in an
431
+ # unambiguous `C:\Bytecode\Somewhere\Foo\Bar\`.
432
+ if not _path_isabs(head):
433
+ head = _path_join(_os.getcwd(), head)
434
+
435
+ # Strip initial drive from a Windows path. We know we have an absolute
436
+ # path here, so the second part of the check rules out a POSIX path that
437
+ # happens to contain a colon at the second character.
438
+ if head[1] == ':' and head[0] not in path_separators:
439
+ head = head[2:]
440
+
441
+ # Strip initial path separator from `head` to complete the conversion
442
+ # back to a root-relative path before joining.
443
+ return _path_join(
444
+ sys.pycache_prefix,
445
+ head.lstrip(path_separators),
446
+ filename,
447
+ )
448
+ return _path_join(head, _PYCACHE, filename)
449
+
450
+
451
+ def source_from_cache(path):
452
+ """Given the path to a .pyc. file, return the path to its .py file.
453
+
454
+ The .pyc file does not need to exist; this simply returns the path to
455
+ the .py file calculated to correspond to the .pyc file. If path does
456
+ not conform to PEP 3147/488 format, ValueError will be raised. If
457
+ sys.implementation.cache_tag is None then NotImplementedError is raised.
458
+
459
+ """
460
+ if sys.implementation.cache_tag is None:
461
+ raise NotImplementedError('sys.implementation.cache_tag is None')
462
+ path = _os.fspath(path)
463
+ head, pycache_filename = _path_split(path)
464
+ found_in_pycache_prefix = False
465
+ if sys.pycache_prefix is not None:
466
+ stripped_path = sys.pycache_prefix.rstrip(path_separators)
467
+ if head.startswith(stripped_path + path_sep):
468
+ head = head[len(stripped_path):]
469
+ found_in_pycache_prefix = True
470
+ if not found_in_pycache_prefix:
471
+ head, pycache = _path_split(head)
472
+ if pycache != _PYCACHE:
473
+ raise ValueError(f'{_PYCACHE} not bottom-level directory in '
474
+ f'{path!r}')
475
+ dot_count = pycache_filename.count('.')
476
+ if dot_count not in {2, 3}:
477
+ raise ValueError(f'expected only 2 or 3 dots in {pycache_filename!r}')
478
+ elif dot_count == 3:
479
+ optimization = pycache_filename.rsplit('.', 2)[-2]
480
+ if not optimization.startswith(_OPT):
481
+ raise ValueError("optimization portion of filename does not start "
482
+ f"with {_OPT!r}")
483
+ opt_level = optimization[len(_OPT):]
484
+ if not opt_level.isalnum():
485
+ raise ValueError(f"optimization level {optimization!r} is not an "
486
+ "alphanumeric value")
487
+ base_filename = pycache_filename.partition('.')[0]
488
+ return _path_join(head, base_filename + SOURCE_SUFFIXES[0])
489
+
490
+
491
+ def _get_sourcefile(bytecode_path):
492
+ """Convert a bytecode file path to a source path (if possible).
493
+
494
+ This function exists purely for backwards-compatibility for
495
+ PyImport_ExecCodeModuleWithFilenames() in the C API.
496
+
497
+ """
498
+ if len(bytecode_path) == 0:
499
+ return None
500
+ rest, _, extension = bytecode_path.rpartition('.')
501
+ if not rest or extension.lower()[-3:-1] != 'py':
502
+ return bytecode_path
503
+ try:
504
+ source_path = source_from_cache(bytecode_path)
505
+ except (NotImplementedError, ValueError):
506
+ source_path = bytecode_path[:-1]
507
+ return source_path if _path_isfile(source_path) else bytecode_path
508
+
509
+
510
+ def _get_cached(filename):
511
+ if filename.endswith(tuple(SOURCE_SUFFIXES)):
512
+ try:
513
+ return cache_from_source(filename)
514
+ except NotImplementedError:
515
+ pass
516
+ elif filename.endswith(tuple(BYTECODE_SUFFIXES)):
517
+ return filename
518
+ else:
519
+ return None
520
+
521
+
522
+ def _calc_mode(path):
523
+ """Calculate the mode permissions for a bytecode file."""
524
+ try:
525
+ mode = _path_stat(path).st_mode
526
+ except OSError:
527
+ mode = 0o666
528
+ # We always ensure write access so we can update cached files
529
+ # later even when the source files are read-only on Windows (#6074)
530
+ mode |= 0o200
531
+ return mode
532
+
533
+
534
+ def _check_name(method):
535
+ """Decorator to verify that the module being requested matches the one the
536
+ loader can handle.
537
+
538
+ The first argument (self) must define _name which the second argument is
539
+ compared against. If the comparison fails then ImportError is raised.
540
+
541
+ """
542
+ def _check_name_wrapper(self, name=None, *args, **kwargs):
543
+ if name is None:
544
+ name = self.name
545
+ elif self.name != name:
546
+ raise ImportError('loader for %s cannot handle %s' %
547
+ (self.name, name), name=name)
548
+ return method(self, name, *args, **kwargs)
549
+
550
+ # FIXME: @_check_name is used to define class methods before the
551
+ # _bootstrap module is set by _set_bootstrap_module().
552
+ if _bootstrap is not None:
553
+ _wrap = _bootstrap._wrap
554
+ else:
555
+ def _wrap(new, old):
556
+ for replace in ['__module__', '__name__', '__qualname__', '__doc__']:
557
+ if hasattr(old, replace):
558
+ setattr(new, replace, getattr(old, replace))
559
+ new.__dict__.update(old.__dict__)
560
+
561
+ _wrap(_check_name_wrapper, method)
562
+ return _check_name_wrapper
563
+
564
+
565
+ def _find_module_shim(self, fullname):
566
+ """Try to find a loader for the specified module by delegating to
567
+ self.find_loader().
568
+
569
+ This method is deprecated in favor of finder.find_spec().
570
+
571
+ """
572
+ _warnings.warn("find_module() is deprecated and "
573
+ "slated for removal in Python 3.12; use find_spec() instead",
574
+ DeprecationWarning)
575
+ # Call find_loader(). If it returns a string (indicating this
576
+ # is a namespace package portion), generate a warning and
577
+ # return None.
578
+ loader, portions = self.find_loader(fullname)
579
+ if loader is None and len(portions):
580
+ msg = 'Not importing directory {}: missing __init__'
581
+ _warnings.warn(msg.format(portions[0]), ImportWarning)
582
+ return loader
583
+
584
+
585
+ def _classify_pyc(data, name, exc_details):
586
+ """Perform basic validity checking of a pyc header and return the flags field,
587
+ which determines how the pyc should be further validated against the source.
588
+
589
+ *data* is the contents of the pyc file. (Only the first 16 bytes are
590
+ required, though.)
591
+
592
+ *name* is the name of the module being imported. It is used for logging.
593
+
594
+ *exc_details* is a dictionary passed to ImportError if it raised for
595
+ improved debugging.
596
+
597
+ ImportError is raised when the magic number is incorrect or when the flags
598
+ field is invalid. EOFError is raised when the data is found to be truncated.
599
+
600
+ """
601
+ magic = data[:4]
602
+ if magic != MAGIC_NUMBER:
603
+ message = f'bad magic number in {name!r}: {magic!r}'
604
+ _bootstrap._verbose_message('{}', message)
605
+ raise ImportError(message, **exc_details)
606
+ if len(data) < 16:
607
+ message = f'reached EOF while reading pyc header of {name!r}'
608
+ _bootstrap._verbose_message('{}', message)
609
+ raise EOFError(message)
610
+ flags = _unpack_uint32(data[4:8])
611
+ # Only the first two flags are defined.
612
+ if flags & ~0b11:
613
+ message = f'invalid flags {flags!r} in {name!r}'
614
+ raise ImportError(message, **exc_details)
615
+ return flags
616
+
617
+
618
+ def _validate_timestamp_pyc(data, source_mtime, source_size, name,
619
+ exc_details):
620
+ """Validate a pyc against the source last-modified time.
621
+
622
+ *data* is the contents of the pyc file. (Only the first 16 bytes are
623
+ required.)
624
+
625
+ *source_mtime* is the last modified timestamp of the source file.
626
+
627
+ *source_size* is None or the size of the source file in bytes.
628
+
629
+ *name* is the name of the module being imported. It is used for logging.
630
+
631
+ *exc_details* is a dictionary passed to ImportError if it raised for
632
+ improved debugging.
633
+
634
+ An ImportError is raised if the bytecode is stale.
635
+
636
+ """
637
+ if _unpack_uint32(data[8:12]) != (source_mtime & 0xFFFFFFFF):
638
+ message = f'bytecode is stale for {name!r}'
639
+ _bootstrap._verbose_message('{}', message)
640
+ raise ImportError(message, **exc_details)
641
+ if (source_size is not None and
642
+ _unpack_uint32(data[12:16]) != (source_size & 0xFFFFFFFF)):
643
+ raise ImportError(f'bytecode is stale for {name!r}', **exc_details)
644
+
645
+
646
+ def _validate_hash_pyc(data, source_hash, name, exc_details):
647
+ """Validate a hash-based pyc by checking the real source hash against the one in
648
+ the pyc header.
649
+
650
+ *data* is the contents of the pyc file. (Only the first 16 bytes are
651
+ required.)
652
+
653
+ *source_hash* is the importlib.util.source_hash() of the source file.
654
+
655
+ *name* is the name of the module being imported. It is used for logging.
656
+
657
+ *exc_details* is a dictionary passed to ImportError if it raised for
658
+ improved debugging.
659
+
660
+ An ImportError is raised if the bytecode is stale.
661
+
662
+ """
663
+ if data[8:16] != source_hash:
664
+ raise ImportError(
665
+ f'hash in bytecode doesn\'t match hash of source {name!r}',
666
+ **exc_details,
667
+ )
668
+
669
+
670
+ def _compile_bytecode(data, name=None, bytecode_path=None, source_path=None):
671
+ """Compile bytecode as found in a pyc."""
672
+ code = marshal.loads(data)
673
+ if isinstance(code, _code_type):
674
+ _bootstrap._verbose_message('code object from {!r}', bytecode_path)
675
+ if source_path is not None:
676
+ _imp._fix_co_filename(code, source_path)
677
+ return code
678
+ else:
679
+ raise ImportError('Non-code object in {!r}'.format(bytecode_path),
680
+ name=name, path=bytecode_path)
681
+
682
+
683
+ def _code_to_timestamp_pyc(code, mtime=0, source_size=0):
684
+ "Produce the data for a timestamp-based pyc."
685
+ data = bytearray(MAGIC_NUMBER)
686
+ data.extend(_pack_uint32(0))
687
+ data.extend(_pack_uint32(mtime))
688
+ data.extend(_pack_uint32(source_size))
689
+ data.extend(marshal.dumps(code))
690
+ return data
691
+
692
+
693
+ def _code_to_hash_pyc(code, source_hash, checked=True):
694
+ "Produce the data for a hash-based pyc."
695
+ data = bytearray(MAGIC_NUMBER)
696
+ flags = 0b1 | checked << 1
697
+ data.extend(_pack_uint32(flags))
698
+ assert len(source_hash) == 8
699
+ data.extend(source_hash)
700
+ data.extend(marshal.dumps(code))
701
+ return data
702
+
703
+
704
+ def decode_source(source_bytes):
705
+ """Decode bytes representing source code and return the string.
706
+
707
+ Universal newline support is used in the decoding.
708
+ """
709
+ import tokenize # To avoid bootstrap issues.
710
+ source_bytes_readline = _io.BytesIO(source_bytes).readline
711
+ encoding = tokenize.detect_encoding(source_bytes_readline)
712
+ newline_decoder = _io.IncrementalNewlineDecoder(None, True)
713
+ return newline_decoder.decode(source_bytes.decode(encoding[0]))
714
+
715
+
716
+ # Module specifications #######################################################
717
+
718
+ _POPULATE = object()
719
+
720
+
721
+ def spec_from_file_location(name, location=None, *, loader=None,
722
+ submodule_search_locations=_POPULATE):
723
+ """Return a module spec based on a file location.
724
+
725
+ To indicate that the module is a package, set
726
+ submodule_search_locations to a list of directory paths. An
727
+ empty list is sufficient, though its not otherwise useful to the
728
+ import system.
729
+
730
+ The loader must take a spec as its only __init__() arg.
731
+
732
+ """
733
+ if location is None:
734
+ # The caller may simply want a partially populated location-
735
+ # oriented spec. So we set the location to a bogus value and
736
+ # fill in as much as we can.
737
+ location = '<unknown>'
738
+ if hasattr(loader, 'get_filename'):
739
+ # ExecutionLoader
740
+ try:
741
+ location = loader.get_filename(name)
742
+ except ImportError:
743
+ pass
744
+ else:
745
+ location = _os.fspath(location)
746
+ if not _path_isabs(location):
747
+ try:
748
+ location = _path_join(_os.getcwd(), location)
749
+ except OSError:
750
+ pass
751
+
752
+ # If the location is on the filesystem, but doesn't actually exist,
753
+ # we could return None here, indicating that the location is not
754
+ # valid. However, we don't have a good way of testing since an
755
+ # indirect location (e.g. a zip file or URL) will look like a
756
+ # non-existent file relative to the filesystem.
757
+
758
+ spec = _bootstrap.ModuleSpec(name, loader, origin=location)
759
+ spec._set_fileattr = True
760
+
761
+ # Pick a loader if one wasn't provided.
762
+ if loader is None:
763
+ for loader_class, suffixes in _get_supported_file_loaders():
764
+ if location.endswith(tuple(suffixes)):
765
+ loader = loader_class(name, location)
766
+ spec.loader = loader
767
+ break
768
+ else:
769
+ return None
770
+
771
+ # Set submodule_search_paths appropriately.
772
+ if submodule_search_locations is _POPULATE:
773
+ # Check the loader.
774
+ if hasattr(loader, 'is_package'):
775
+ try:
776
+ is_package = loader.is_package(name)
777
+ except ImportError:
778
+ pass
779
+ else:
780
+ if is_package:
781
+ spec.submodule_search_locations = []
782
+ else:
783
+ spec.submodule_search_locations = submodule_search_locations
784
+ if spec.submodule_search_locations == []:
785
+ if location:
786
+ dirname = _path_split(location)[0]
787
+ spec.submodule_search_locations.append(dirname)
788
+
789
+ return spec
790
+
791
+
792
+ # Loaders #####################################################################
793
+
794
+ class WindowsRegistryFinder:
795
+
796
+ """Meta path finder for modules declared in the Windows registry."""
797
+
798
+ REGISTRY_KEY = (
799
+ 'Software\\Python\\PythonCore\\{sys_version}'
800
+ '\\Modules\\{fullname}')
801
+ REGISTRY_KEY_DEBUG = (
802
+ 'Software\\Python\\PythonCore\\{sys_version}'
803
+ '\\Modules\\{fullname}\\Debug')
804
+ DEBUG_BUILD = (_MS_WINDOWS and '_d.pyd' in EXTENSION_SUFFIXES)
805
+
806
+ @staticmethod
807
+ def _open_registry(key):
808
+ try:
809
+ return winreg.OpenKey(winreg.HKEY_CURRENT_USER, key)
810
+ except OSError:
811
+ return winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key)
812
+
813
+ @classmethod
814
+ def _search_registry(cls, fullname):
815
+ if cls.DEBUG_BUILD:
816
+ registry_key = cls.REGISTRY_KEY_DEBUG
817
+ else:
818
+ registry_key = cls.REGISTRY_KEY
819
+ key = registry_key.format(fullname=fullname,
820
+ sys_version='%d.%d' % sys.version_info[:2])
821
+ try:
822
+ with cls._open_registry(key) as hkey:
823
+ filepath = winreg.QueryValue(hkey, '')
824
+ except OSError:
825
+ return None
826
+ return filepath
827
+
828
+ @classmethod
829
+ def find_spec(cls, fullname, path=None, target=None):
830
+ filepath = cls._search_registry(fullname)
831
+ if filepath is None:
832
+ return None
833
+ try:
834
+ _path_stat(filepath)
835
+ except OSError:
836
+ return None
837
+ for loader, suffixes in _get_supported_file_loaders():
838
+ if filepath.endswith(tuple(suffixes)):
839
+ spec = _bootstrap.spec_from_loader(fullname,
840
+ loader(fullname, filepath),
841
+ origin=filepath)
842
+ return spec
843
+
844
+ @classmethod
845
+ def find_module(cls, fullname, path=None):
846
+ """Find module named in the registry.
847
+
848
+ This method is deprecated. Use find_spec() instead.
849
+
850
+ """
851
+ _warnings.warn("WindowsRegistryFinder.find_module() is deprecated and "
852
+ "slated for removal in Python 3.12; use find_spec() instead",
853
+ DeprecationWarning)
854
+ spec = cls.find_spec(fullname, path)
855
+ if spec is not None:
856
+ return spec.loader
857
+ else:
858
+ return None
859
+
860
+
861
+ class _LoaderBasics:
862
+
863
+ """Base class of common code needed by both SourceLoader and
864
+ SourcelessFileLoader."""
865
+
866
+ def is_package(self, fullname):
867
+ """Concrete implementation of InspectLoader.is_package by checking if
868
+ the path returned by get_filename has a filename of '__init__.py'."""
869
+ filename = _path_split(self.get_filename(fullname))[1]
870
+ filename_base = filename.rsplit('.', 1)[0]
871
+ tail_name = fullname.rpartition('.')[2]
872
+ return filename_base == '__init__' and tail_name != '__init__'
873
+
874
+ def create_module(self, spec):
875
+ """Use default semantics for module creation."""
876
+
877
+ def exec_module(self, module):
878
+ """Execute the module."""
879
+ code = self.get_code(module.__name__)
880
+ if code is None:
881
+ raise ImportError('cannot load module {!r} when get_code() '
882
+ 'returns None'.format(module.__name__))
883
+ _bootstrap._call_with_frames_removed(exec, code, module.__dict__)
884
+
885
+ def load_module(self, fullname):
886
+ """This method is deprecated."""
887
+ # Warning implemented in _load_module_shim().
888
+ return _bootstrap._load_module_shim(self, fullname)
889
+
890
+
891
+ class SourceLoader(_LoaderBasics):
892
+
893
+ def path_mtime(self, path):
894
+ """Optional method that returns the modification time (an int) for the
895
+ specified path (a str).
896
+
897
+ Raises OSError when the path cannot be handled.
898
+ """
899
+ raise OSError
900
+
901
+ def path_stats(self, path):
902
+ """Optional method returning a metadata dict for the specified
903
+ path (a str).
904
+
905
+ Possible keys:
906
+ - 'mtime' (mandatory) is the numeric timestamp of last source
907
+ code modification;
908
+ - 'size' (optional) is the size in bytes of the source code.
909
+
910
+ Implementing this method allows the loader to read bytecode files.
911
+ Raises OSError when the path cannot be handled.
912
+ """
913
+ return {'mtime': self.path_mtime(path)}
914
+
915
+ def _cache_bytecode(self, source_path, cache_path, data):
916
+ """Optional method which writes data (bytes) to a file path (a str).
917
+
918
+ Implementing this method allows for the writing of bytecode files.
919
+
920
+ The source path is needed in order to correctly transfer permissions
921
+ """
922
+ # For backwards compatibility, we delegate to set_data()
923
+ return self.set_data(cache_path, data)
924
+
925
+ def set_data(self, path, data):
926
+ """Optional method which writes data (bytes) to a file path (a str).
927
+
928
+ Implementing this method allows for the writing of bytecode files.
929
+ """
930
+
931
+
932
+ def get_source(self, fullname):
933
+ """Concrete implementation of InspectLoader.get_source."""
934
+ path = self.get_filename(fullname)
935
+ try:
936
+ source_bytes = self.get_data(path)
937
+ except OSError as exc:
938
+ raise ImportError('source not available through get_data()',
939
+ name=fullname) from exc
940
+ return decode_source(source_bytes)
941
+
942
+ def source_to_code(self, data, path, *, _optimize=-1):
943
+ """Return the code object compiled from source.
944
+
945
+ The 'data' argument can be any object type that compile() supports.
946
+ """
947
+ return _bootstrap._call_with_frames_removed(compile, data, path, 'exec',
948
+ dont_inherit=True, optimize=_optimize)
949
+
950
+ def get_code(self, fullname):
951
+ """Concrete implementation of InspectLoader.get_code.
952
+
953
+ Reading of bytecode requires path_stats to be implemented. To write
954
+ bytecode, set_data must also be implemented.
955
+
956
+ """
957
+ source_path = self.get_filename(fullname)
958
+ source_mtime = None
959
+ source_bytes = None
960
+ source_hash = None
961
+ hash_based = False
962
+ check_source = True
963
+ try:
964
+ bytecode_path = cache_from_source(source_path)
965
+ except NotImplementedError:
966
+ bytecode_path = None
967
+ else:
968
+ try:
969
+ st = self.path_stats(source_path)
970
+ except OSError:
971
+ pass
972
+ else:
973
+ source_mtime = int(st['mtime'])
974
+ try:
975
+ data = self.get_data(bytecode_path)
976
+ except OSError:
977
+ pass
978
+ else:
979
+ exc_details = {
980
+ 'name': fullname,
981
+ 'path': bytecode_path,
982
+ }
983
+ try:
984
+ flags = _classify_pyc(data, fullname, exc_details)
985
+ bytes_data = memoryview(data)[16:]
986
+ hash_based = flags & 0b1 != 0
987
+ if hash_based:
988
+ check_source = flags & 0b10 != 0
989
+ if (_imp.check_hash_based_pycs != 'never' and
990
+ (check_source or
991
+ _imp.check_hash_based_pycs == 'always')):
992
+ source_bytes = self.get_data(source_path)
993
+ source_hash = _imp.source_hash(
994
+ _RAW_MAGIC_NUMBER,
995
+ source_bytes,
996
+ )
997
+ _validate_hash_pyc(data, source_hash, fullname,
998
+ exc_details)
999
+ else:
1000
+ _validate_timestamp_pyc(
1001
+ data,
1002
+ source_mtime,
1003
+ st['size'],
1004
+ fullname,
1005
+ exc_details,
1006
+ )
1007
+ except (ImportError, EOFError):
1008
+ pass
1009
+ else:
1010
+ _bootstrap._verbose_message('{} matches {}', bytecode_path,
1011
+ source_path)
1012
+ return _compile_bytecode(bytes_data, name=fullname,
1013
+ bytecode_path=bytecode_path,
1014
+ source_path=source_path)
1015
+ if source_bytes is None:
1016
+ source_bytes = self.get_data(source_path)
1017
+ code_object = self.source_to_code(source_bytes, source_path)
1018
+ _bootstrap._verbose_message('code object from {}', source_path)
1019
+ if (not sys.dont_write_bytecode and bytecode_path is not None and
1020
+ source_mtime is not None):
1021
+ if hash_based:
1022
+ if source_hash is None:
1023
+ source_hash = _imp.source_hash(source_bytes)
1024
+ data = _code_to_hash_pyc(code_object, source_hash, check_source)
1025
+ else:
1026
+ data = _code_to_timestamp_pyc(code_object, source_mtime,
1027
+ len(source_bytes))
1028
+ try:
1029
+ self._cache_bytecode(source_path, bytecode_path, data)
1030
+ except NotImplementedError:
1031
+ pass
1032
+ return code_object
1033
+
1034
+
1035
+ class FileLoader:
1036
+
1037
+ """Base file loader class which implements the loader protocol methods that
1038
+ require file system usage."""
1039
+
1040
+ def __init__(self, fullname, path):
1041
+ """Cache the module name and the path to the file found by the
1042
+ finder."""
1043
+ self.name = fullname
1044
+ self.path = path
1045
+
1046
+ def __eq__(self, other):
1047
+ return (self.__class__ == other.__class__ and
1048
+ self.__dict__ == other.__dict__)
1049
+
1050
+ def __hash__(self):
1051
+ return hash(self.name) ^ hash(self.path)
1052
+
1053
+ @_check_name
1054
+ def load_module(self, fullname):
1055
+ """Load a module from a file.
1056
+
1057
+ This method is deprecated. Use exec_module() instead.
1058
+
1059
+ """
1060
+ # The only reason for this method is for the name check.
1061
+ # Issue #14857: Avoid the zero-argument form of super so the implementation
1062
+ # of that form can be updated without breaking the frozen module.
1063
+ return super(FileLoader, self).load_module(fullname)
1064
+
1065
+ @_check_name
1066
+ def get_filename(self, fullname):
1067
+ """Return the path to the source file as found by the finder."""
1068
+ return self.path
1069
+
1070
+ def get_data(self, path):
1071
+ """Return the data from path as raw bytes."""
1072
+ if isinstance(self, (SourceLoader, ExtensionFileLoader)):
1073
+ with _io.open_code(str(path)) as file:
1074
+ return file.read()
1075
+ else:
1076
+ with _io.FileIO(path, 'r') as file:
1077
+ return file.read()
1078
+
1079
+ @_check_name
1080
+ def get_resource_reader(self, module):
1081
+ from importlib.readers import FileReader
1082
+ return FileReader(self)
1083
+
1084
+
1085
+ class SourceFileLoader(FileLoader, SourceLoader):
1086
+
1087
+ """Concrete implementation of SourceLoader using the file system."""
1088
+
1089
+ def path_stats(self, path):
1090
+ """Return the metadata for the path."""
1091
+ st = _path_stat(path)
1092
+ return {'mtime': st.st_mtime, 'size': st.st_size}
1093
+
1094
+ def _cache_bytecode(self, source_path, bytecode_path, data):
1095
+ # Adapt between the two APIs
1096
+ mode = _calc_mode(source_path)
1097
+ return self.set_data(bytecode_path, data, _mode=mode)
1098
+
1099
+ def set_data(self, path, data, *, _mode=0o666):
1100
+ """Write bytes data to a file."""
1101
+ parent, filename = _path_split(path)
1102
+ path_parts = []
1103
+ # Figure out what directories are missing.
1104
+ while parent and not _path_isdir(parent):
1105
+ parent, part = _path_split(parent)
1106
+ path_parts.append(part)
1107
+ # Create needed directories.
1108
+ for part in reversed(path_parts):
1109
+ parent = _path_join(parent, part)
1110
+ try:
1111
+ _os.mkdir(parent)
1112
+ except FileExistsError:
1113
+ # Probably another Python process already created the dir.
1114
+ continue
1115
+ except OSError as exc:
1116
+ # Could be a permission error, read-only filesystem: just forget
1117
+ # about writing the data.
1118
+ _bootstrap._verbose_message('could not create {!r}: {!r}',
1119
+ parent, exc)
1120
+ return
1121
+ try:
1122
+ _write_atomic(path, data, _mode)
1123
+ _bootstrap._verbose_message('created {!r}', path)
1124
+ except OSError as exc:
1125
+ # Same as above: just don't write the bytecode.
1126
+ _bootstrap._verbose_message('could not create {!r}: {!r}', path,
1127
+ exc)
1128
+
1129
+
1130
+ class SourcelessFileLoader(FileLoader, _LoaderBasics):
1131
+
1132
+ """Loader which handles sourceless file imports."""
1133
+
1134
+ def get_code(self, fullname):
1135
+ path = self.get_filename(fullname)
1136
+ data = self.get_data(path)
1137
+ # Call _classify_pyc to do basic validation of the pyc but ignore the
1138
+ # result. There's no source to check against.
1139
+ exc_details = {
1140
+ 'name': fullname,
1141
+ 'path': path,
1142
+ }
1143
+ _classify_pyc(data, fullname, exc_details)
1144
+ return _compile_bytecode(
1145
+ memoryview(data)[16:],
1146
+ name=fullname,
1147
+ bytecode_path=path,
1148
+ )
1149
+
1150
+ def get_source(self, fullname):
1151
+ """Return None as there is no source code."""
1152
+ return None
1153
+
1154
+
1155
+ class ExtensionFileLoader(FileLoader, _LoaderBasics):
1156
+
1157
+ """Loader for extension modules.
1158
+
1159
+ The constructor is designed to work with FileFinder.
1160
+
1161
+ """
1162
+
1163
+ def __init__(self, name, path):
1164
+ self.name = name
1165
+ self.path = path
1166
+
1167
+ def __eq__(self, other):
1168
+ return (self.__class__ == other.__class__ and
1169
+ self.__dict__ == other.__dict__)
1170
+
1171
+ def __hash__(self):
1172
+ return hash(self.name) ^ hash(self.path)
1173
+
1174
+ def create_module(self, spec):
1175
+ """Create an unitialized extension module"""
1176
+ module = _bootstrap._call_with_frames_removed(
1177
+ _imp.create_dynamic, spec)
1178
+ _bootstrap._verbose_message('extension module {!r} loaded from {!r}',
1179
+ spec.name, self.path)
1180
+ return module
1181
+
1182
+ def exec_module(self, module):
1183
+ """Initialize an extension module"""
1184
+ _bootstrap._call_with_frames_removed(_imp.exec_dynamic, module)
1185
+ _bootstrap._verbose_message('extension module {!r} executed from {!r}',
1186
+ self.name, self.path)
1187
+
1188
+ def is_package(self, fullname):
1189
+ """Return True if the extension module is a package."""
1190
+ file_name = _path_split(self.path)[1]
1191
+ return any(file_name == '__init__' + suffix
1192
+ for suffix in EXTENSION_SUFFIXES)
1193
+
1194
+ def get_code(self, fullname):
1195
+ """Return None as an extension module cannot create a code object."""
1196
+ return None
1197
+
1198
+ def get_source(self, fullname):
1199
+ """Return None as extension modules have no source code."""
1200
+ return None
1201
+
1202
+ @_check_name
1203
+ def get_filename(self, fullname):
1204
+ """Return the path to the source file as found by the finder."""
1205
+ return self.path
1206
+
1207
+
1208
+ class _NamespacePath:
1209
+ """Represents a namespace package's path. It uses the module name
1210
+ to find its parent module, and from there it looks up the parent's
1211
+ __path__. When this changes, the module's own path is recomputed,
1212
+ using path_finder. For top-level modules, the parent module's path
1213
+ is sys.path."""
1214
+
1215
+ # When invalidate_caches() is called, this epoch is incremented
1216
+ # https://bugs.python.org/issue45703
1217
+ _epoch = 0
1218
+
1219
+ def __init__(self, name, path, path_finder):
1220
+ self._name = name
1221
+ self._path = path
1222
+ self._last_parent_path = tuple(self._get_parent_path())
1223
+ self._last_epoch = self._epoch
1224
+ self._path_finder = path_finder
1225
+
1226
+ def _find_parent_path_names(self):
1227
+ """Returns a tuple of (parent-module-name, parent-path-attr-name)"""
1228
+ parent, dot, me = self._name.rpartition('.')
1229
+ if dot == '':
1230
+ # This is a top-level module. sys.path contains the parent path.
1231
+ return 'sys', 'path'
1232
+ # Not a top-level module. parent-module.__path__ contains the
1233
+ # parent path.
1234
+ return parent, '__path__'
1235
+
1236
+ def _get_parent_path(self):
1237
+ parent_module_name, path_attr_name = self._find_parent_path_names()
1238
+ return getattr(sys.modules[parent_module_name], path_attr_name)
1239
+
1240
+ def _recalculate(self):
1241
+ # If the parent's path has changed, recalculate _path
1242
+ parent_path = tuple(self._get_parent_path()) # Make a copy
1243
+ if parent_path != self._last_parent_path or self._epoch != self._last_epoch:
1244
+ spec = self._path_finder(self._name, parent_path)
1245
+ # Note that no changes are made if a loader is returned, but we
1246
+ # do remember the new parent path
1247
+ if spec is not None and spec.loader is None:
1248
+ if spec.submodule_search_locations:
1249
+ self._path = spec.submodule_search_locations
1250
+ self._last_parent_path = parent_path # Save the copy
1251
+ self._last_epoch = self._epoch
1252
+ return self._path
1253
+
1254
+ def __iter__(self):
1255
+ return iter(self._recalculate())
1256
+
1257
+ def __getitem__(self, index):
1258
+ return self._recalculate()[index]
1259
+
1260
+ def __setitem__(self, index, path):
1261
+ self._path[index] = path
1262
+
1263
+ def __len__(self):
1264
+ return len(self._recalculate())
1265
+
1266
+ def __repr__(self):
1267
+ return '_NamespacePath({!r})'.format(self._path)
1268
+
1269
+ def __contains__(self, item):
1270
+ return item in self._recalculate()
1271
+
1272
+ def append(self, item):
1273
+ self._path.append(item)
1274
+
1275
+
1276
+ # We use this exclusively in module_from_spec() for backward-compatibility.
1277
+ class _NamespaceLoader:
1278
+ def __init__(self, name, path, path_finder):
1279
+ self._path = _NamespacePath(name, path, path_finder)
1280
+
1281
+ @staticmethod
1282
+ def module_repr(module):
1283
+ """Return repr for the module.
1284
+
1285
+ The method is deprecated. The import machinery does the job itself.
1286
+
1287
+ """
1288
+ _warnings.warn("_NamespaceLoader.module_repr() is deprecated and "
1289
+ "slated for removal in Python 3.12", DeprecationWarning)
1290
+ return '<module {!r} (namespace)>'.format(module.__name__)
1291
+
1292
+ def is_package(self, fullname):
1293
+ return True
1294
+
1295
+ def get_source(self, fullname):
1296
+ return ''
1297
+
1298
+ def get_code(self, fullname):
1299
+ return compile('', '<string>', 'exec', dont_inherit=True)
1300
+
1301
+ def create_module(self, spec):
1302
+ """Use default semantics for module creation."""
1303
+
1304
+ def exec_module(self, module):
1305
+ pass
1306
+
1307
+ def load_module(self, fullname):
1308
+ """Load a namespace module.
1309
+
1310
+ This method is deprecated. Use exec_module() instead.
1311
+
1312
+ """
1313
+ # The import system never calls this method.
1314
+ _bootstrap._verbose_message('namespace module loaded with path {!r}',
1315
+ self._path)
1316
+ # Warning implemented in _load_module_shim().
1317
+ return _bootstrap._load_module_shim(self, fullname)
1318
+
1319
+ def get_resource_reader(self, module):
1320
+ from importlib.readers import NamespaceReader
1321
+ return NamespaceReader(self._path)
1322
+
1323
+
1324
+ # Finders #####################################################################
1325
+
1326
+ class PathFinder:
1327
+
1328
+ """Meta path finder for sys.path and package __path__ attributes."""
1329
+
1330
+ @staticmethod
1331
+ def invalidate_caches():
1332
+ """Call the invalidate_caches() method on all path entry finders
1333
+ stored in sys.path_importer_caches (where implemented)."""
1334
+ for name, finder in list(sys.path_importer_cache.items()):
1335
+ if finder is None:
1336
+ del sys.path_importer_cache[name]
1337
+ elif hasattr(finder, 'invalidate_caches'):
1338
+ finder.invalidate_caches()
1339
+ # Also invalidate the caches of _NamespacePaths
1340
+ # https://bugs.python.org/issue45703
1341
+ _NamespacePath._epoch += 1
1342
+
1343
+ @staticmethod
1344
+ def _path_hooks(path):
1345
+ """Search sys.path_hooks for a finder for 'path'."""
1346
+ if sys.path_hooks is not None and not sys.path_hooks:
1347
+ _warnings.warn('sys.path_hooks is empty', ImportWarning)
1348
+ for hook in sys.path_hooks:
1349
+ try:
1350
+ return hook(path)
1351
+ except ImportError:
1352
+ continue
1353
+ else:
1354
+ return None
1355
+
1356
+ @classmethod
1357
+ def _path_importer_cache(cls, path):
1358
+ """Get the finder for the path entry from sys.path_importer_cache.
1359
+
1360
+ If the path entry is not in the cache, find the appropriate finder
1361
+ and cache it. If no finder is available, store None.
1362
+
1363
+ """
1364
+ if path == '':
1365
+ try:
1366
+ path = _os.getcwd()
1367
+ except FileNotFoundError:
1368
+ # Don't cache the failure as the cwd can easily change to
1369
+ # a valid directory later on.
1370
+ return None
1371
+ try:
1372
+ finder = sys.path_importer_cache[path]
1373
+ except KeyError:
1374
+ finder = cls._path_hooks(path)
1375
+ sys.path_importer_cache[path] = finder
1376
+ return finder
1377
+
1378
+ @classmethod
1379
+ def _legacy_get_spec(cls, fullname, finder):
1380
+ # This would be a good place for a DeprecationWarning if
1381
+ # we ended up going that route.
1382
+ if hasattr(finder, 'find_loader'):
1383
+ msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; "
1384
+ "falling back to find_loader()")
1385
+ _warnings.warn(msg, ImportWarning)
1386
+ loader, portions = finder.find_loader(fullname)
1387
+ else:
1388
+ msg = (f"{_bootstrap._object_name(finder)}.find_spec() not found; "
1389
+ "falling back to find_module()")
1390
+ _warnings.warn(msg, ImportWarning)
1391
+ loader = finder.find_module(fullname)
1392
+ portions = []
1393
+ if loader is not None:
1394
+ return _bootstrap.spec_from_loader(fullname, loader)
1395
+ spec = _bootstrap.ModuleSpec(fullname, None)
1396
+ spec.submodule_search_locations = portions
1397
+ return spec
1398
+
1399
+ @classmethod
1400
+ def _get_spec(cls, fullname, path, target=None):
1401
+ """Find the loader or namespace_path for this module/package name."""
1402
+ # If this ends up being a namespace package, namespace_path is
1403
+ # the list of paths that will become its __path__
1404
+ namespace_path = []
1405
+ for entry in path:
1406
+ if not isinstance(entry, (str, bytes)):
1407
+ continue
1408
+ finder = cls._path_importer_cache(entry)
1409
+ if finder is not None:
1410
+ if hasattr(finder, 'find_spec'):
1411
+ spec = finder.find_spec(fullname, target)
1412
+ else:
1413
+ spec = cls._legacy_get_spec(fullname, finder)
1414
+ if spec is None:
1415
+ continue
1416
+ if spec.loader is not None:
1417
+ return spec
1418
+ portions = spec.submodule_search_locations
1419
+ if portions is None:
1420
+ raise ImportError('spec missing loader')
1421
+ # This is possibly part of a namespace package.
1422
+ # Remember these path entries (if any) for when we
1423
+ # create a namespace package, and continue iterating
1424
+ # on path.
1425
+ namespace_path.extend(portions)
1426
+ else:
1427
+ spec = _bootstrap.ModuleSpec(fullname, None)
1428
+ spec.submodule_search_locations = namespace_path
1429
+ return spec
1430
+
1431
+ @classmethod
1432
+ def find_spec(cls, fullname, path=None, target=None):
1433
+ """Try to find a spec for 'fullname' on sys.path or 'path'.
1434
+
1435
+ The search is based on sys.path_hooks and sys.path_importer_cache.
1436
+ """
1437
+ if path is None:
1438
+ path = sys.path
1439
+ spec = cls._get_spec(fullname, path, target)
1440
+ if spec is None:
1441
+ return None
1442
+ elif spec.loader is None:
1443
+ namespace_path = spec.submodule_search_locations
1444
+ if namespace_path:
1445
+ # We found at least one namespace path. Return a spec which
1446
+ # can create the namespace package.
1447
+ spec.origin = None
1448
+ spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
1449
+ return spec
1450
+ else:
1451
+ return None
1452
+ else:
1453
+ return spec
1454
+
1455
+ @classmethod
1456
+ def find_module(cls, fullname, path=None):
1457
+ """find the module on sys.path or 'path' based on sys.path_hooks and
1458
+ sys.path_importer_cache.
1459
+
1460
+ This method is deprecated. Use find_spec() instead.
1461
+
1462
+ """
1463
+ _warnings.warn("PathFinder.find_module() is deprecated and "
1464
+ "slated for removal in Python 3.12; use find_spec() instead",
1465
+ DeprecationWarning)
1466
+ spec = cls.find_spec(fullname, path)
1467
+ if spec is None:
1468
+ return None
1469
+ return spec.loader
1470
+
1471
+ @staticmethod
1472
+ def find_distributions(*args, **kwargs):
1473
+ """
1474
+ Find distributions.
1475
+
1476
+ Return an iterable of all Distribution instances capable of
1477
+ loading the metadata for packages matching ``context.name``
1478
+ (or all names if ``None`` indicated) along the paths in the list
1479
+ of directories ``context.path``.
1480
+ """
1481
+ from importlib.metadata import MetadataPathFinder
1482
+ return MetadataPathFinder.find_distributions(*args, **kwargs)
1483
+
1484
+
1485
+ class FileFinder:
1486
+
1487
+ """File-based finder.
1488
+
1489
+ Interactions with the file system are cached for performance, being
1490
+ refreshed when the directory the finder is handling has been modified.
1491
+
1492
+ """
1493
+
1494
+ def __init__(self, path, *loader_details):
1495
+ """Initialize with the path to search on and a variable number of
1496
+ 2-tuples containing the loader and the file suffixes the loader
1497
+ recognizes."""
1498
+ loaders = []
1499
+ for loader, suffixes in loader_details:
1500
+ loaders.extend((suffix, loader) for suffix in suffixes)
1501
+ self._loaders = loaders
1502
+ # Base (directory) path
1503
+ self.path = path or '.'
1504
+ if not _path_isabs(self.path):
1505
+ self.path = _path_join(_os.getcwd(), self.path)
1506
+ self._path_mtime = -1
1507
+ self._path_cache = set()
1508
+ self._relaxed_path_cache = set()
1509
+
1510
+ def invalidate_caches(self):
1511
+ """Invalidate the directory mtime."""
1512
+ self._path_mtime = -1
1513
+
1514
+ find_module = _find_module_shim
1515
+
1516
+ def find_loader(self, fullname):
1517
+ """Try to find a loader for the specified module, or the namespace
1518
+ package portions. Returns (loader, list-of-portions).
1519
+
1520
+ This method is deprecated. Use find_spec() instead.
1521
+
1522
+ """
1523
+ _warnings.warn("FileFinder.find_loader() is deprecated and "
1524
+ "slated for removal in Python 3.12; use find_spec() instead",
1525
+ DeprecationWarning)
1526
+ spec = self.find_spec(fullname)
1527
+ if spec is None:
1528
+ return None, []
1529
+ return spec.loader, spec.submodule_search_locations or []
1530
+
1531
+ def _get_spec(self, loader_class, fullname, path, smsl, target):
1532
+ loader = loader_class(fullname, path)
1533
+ return spec_from_file_location(fullname, path, loader=loader,
1534
+ submodule_search_locations=smsl)
1535
+
1536
+ def find_spec(self, fullname, target=None):
1537
+ """Try to find a spec for the specified module.
1538
+
1539
+ Returns the matching spec, or None if not found.
1540
+ """
1541
+ is_namespace = False
1542
+ tail_module = fullname.rpartition('.')[2]
1543
+ try:
1544
+ mtime = _path_stat(self.path or _os.getcwd()).st_mtime
1545
+ except OSError:
1546
+ mtime = -1
1547
+ if mtime != self._path_mtime:
1548
+ self._fill_cache()
1549
+ self._path_mtime = mtime
1550
+ # tail_module keeps the original casing, for __file__ and friends
1551
+ if _relax_case():
1552
+ cache = self._relaxed_path_cache
1553
+ cache_module = tail_module.lower()
1554
+ else:
1555
+ cache = self._path_cache
1556
+ cache_module = tail_module
1557
+ # Check if the module is the name of a directory (and thus a package).
1558
+ if cache_module in cache:
1559
+ base_path = _path_join(self.path, tail_module)
1560
+ for suffix, loader_class in self._loaders:
1561
+ init_filename = '__init__' + suffix
1562
+ full_path = _path_join(base_path, init_filename)
1563
+ if _path_isfile(full_path):
1564
+ return self._get_spec(loader_class, fullname, full_path, [base_path], target)
1565
+ else:
1566
+ # If a namespace package, return the path if we don't
1567
+ # find a module in the next section.
1568
+ is_namespace = _path_isdir(base_path)
1569
+ # Check for a file w/ a proper suffix exists.
1570
+ for suffix, loader_class in self._loaders:
1571
+ try:
1572
+ full_path = _path_join(self.path, tail_module + suffix)
1573
+ except ValueError:
1574
+ return None
1575
+ _bootstrap._verbose_message('trying {}', full_path, verbosity=2)
1576
+ if cache_module + suffix in cache:
1577
+ if _path_isfile(full_path):
1578
+ return self._get_spec(loader_class, fullname, full_path,
1579
+ None, target)
1580
+ if is_namespace:
1581
+ _bootstrap._verbose_message('possible namespace for {}', base_path)
1582
+ spec = _bootstrap.ModuleSpec(fullname, None)
1583
+ spec.submodule_search_locations = [base_path]
1584
+ return spec
1585
+ return None
1586
+
1587
+ def _fill_cache(self):
1588
+ """Fill the cache of potential modules and packages for this directory."""
1589
+ path = self.path
1590
+ try:
1591
+ contents = _os.listdir(path or _os.getcwd())
1592
+ except (FileNotFoundError, PermissionError, NotADirectoryError):
1593
+ # Directory has either been removed, turned into a file, or made
1594
+ # unreadable.
1595
+ contents = []
1596
+ # We store two cached versions, to handle runtime changes of the
1597
+ # PYTHONCASEOK environment variable.
1598
+ if not sys.platform.startswith('win'):
1599
+ self._path_cache = set(contents)
1600
+ else:
1601
+ # Windows users can import modules with case-insensitive file
1602
+ # suffixes (for legacy reasons). Make the suffix lowercase here
1603
+ # so it's done once instead of for every import. This is safe as
1604
+ # the specified suffixes to check against are always specified in a
1605
+ # case-sensitive manner.
1606
+ lower_suffix_contents = set()
1607
+ for item in contents:
1608
+ name, dot, suffix = item.partition('.')
1609
+ if dot:
1610
+ new_name = '{}.{}'.format(name, suffix.lower())
1611
+ else:
1612
+ new_name = name
1613
+ lower_suffix_contents.add(new_name)
1614
+ self._path_cache = lower_suffix_contents
1615
+ if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
1616
+ self._relaxed_path_cache = {fn.lower() for fn in contents}
1617
+
1618
+ @classmethod
1619
+ def path_hook(cls, *loader_details):
1620
+ """A class method which returns a closure to use on sys.path_hook
1621
+ which will return an instance using the specified loaders and the path
1622
+ called on the closure.
1623
+
1624
+ If the path called on the closure is not a directory, ImportError is
1625
+ raised.
1626
+
1627
+ """
1628
+ def path_hook_for_FileFinder(path):
1629
+ """Path hook for importlib.machinery.FileFinder."""
1630
+ if not _path_isdir(path):
1631
+ raise ImportError('only directories are supported', path=path)
1632
+ return cls(path, *loader_details)
1633
+
1634
+ return path_hook_for_FileFinder
1635
+
1636
+ def __repr__(self):
1637
+ return 'FileFinder({!r})'.format(self.path)
1638
+
1639
+
1640
+ # Import setup ###############################################################
1641
+
1642
+ def _fix_up_module(ns, name, pathname, cpathname=None):
1643
+ # This function is used by PyImport_ExecCodeModuleObject().
1644
+ loader = ns.get('__loader__')
1645
+ spec = ns.get('__spec__')
1646
+ if not loader:
1647
+ if spec:
1648
+ loader = spec.loader
1649
+ elif pathname == cpathname:
1650
+ loader = SourcelessFileLoader(name, pathname)
1651
+ else:
1652
+ loader = SourceFileLoader(name, pathname)
1653
+ if not spec:
1654
+ spec = spec_from_file_location(name, pathname, loader=loader)
1655
+ try:
1656
+ ns['__spec__'] = spec
1657
+ ns['__loader__'] = loader
1658
+ ns['__file__'] = pathname
1659
+ ns['__cached__'] = cpathname
1660
+ except Exception:
1661
+ # Not important enough to report.
1662
+ pass
1663
+
1664
+
1665
+ def _get_supported_file_loaders():
1666
+ """Returns a list of file-based module loaders.
1667
+
1668
+ Each item is a tuple (loader, suffixes).
1669
+ """
1670
+ extensions = ExtensionFileLoader, _imp.extension_suffixes()
1671
+ source = SourceFileLoader, SOURCE_SUFFIXES
1672
+ bytecode = SourcelessFileLoader, BYTECODE_SUFFIXES
1673
+ return [extensions, source, bytecode]
1674
+
1675
+
1676
+ def _set_bootstrap_module(_bootstrap_module):
1677
+ global _bootstrap
1678
+ _bootstrap = _bootstrap_module
1679
+
1680
+
1681
+ def _install(_bootstrap_module):
1682
+ """Install the path-based import components."""
1683
+ _set_bootstrap_module(_bootstrap_module)
1684
+ supported_loaders = _get_supported_file_loaders()
1685
+ sys.path_hooks.extend([FileFinder.path_hook(*supported_loaders)])
1686
+ sys.meta_path.append(PathFinder)
parrot/lib/python3.10/importlib/util.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility code for constructing importers, etc."""
2
+ from ._abc import Loader
3
+ from ._bootstrap import module_from_spec
4
+ from ._bootstrap import _resolve_name
5
+ from ._bootstrap import spec_from_loader
6
+ from ._bootstrap import _find_spec
7
+ from ._bootstrap_external import MAGIC_NUMBER
8
+ from ._bootstrap_external import _RAW_MAGIC_NUMBER
9
+ from ._bootstrap_external import cache_from_source
10
+ from ._bootstrap_external import decode_source
11
+ from ._bootstrap_external import source_from_cache
12
+ from ._bootstrap_external import spec_from_file_location
13
+
14
+ from contextlib import contextmanager
15
+ import _imp
16
+ import functools
17
+ import sys
18
+ import types
19
+ import warnings
20
+
21
+
22
+ def source_hash(source_bytes):
23
+ "Return the hash of *source_bytes* as used in hash-based pyc files."
24
+ return _imp.source_hash(_RAW_MAGIC_NUMBER, source_bytes)
25
+
26
+
27
+ def resolve_name(name, package):
28
+ """Resolve a relative module name to an absolute one."""
29
+ if not name.startswith('.'):
30
+ return name
31
+ elif not package:
32
+ raise ImportError(f'no package specified for {repr(name)} '
33
+ '(required for relative module names)')
34
+ level = 0
35
+ for character in name:
36
+ if character != '.':
37
+ break
38
+ level += 1
39
+ return _resolve_name(name[level:], package, level)
40
+
41
+
42
+ def _find_spec_from_path(name, path=None):
43
+ """Return the spec for the specified module.
44
+
45
+ First, sys.modules is checked to see if the module was already imported. If
46
+ so, then sys.modules[name].__spec__ is returned. If that happens to be
47
+ set to None, then ValueError is raised. If the module is not in
48
+ sys.modules, then sys.meta_path is searched for a suitable spec with the
49
+ value of 'path' given to the finders. None is returned if no spec could
50
+ be found.
51
+
52
+ Dotted names do not have their parent packages implicitly imported. You will
53
+ most likely need to explicitly import all parent packages in the proper
54
+ order for a submodule to get the correct spec.
55
+
56
+ """
57
+ if name not in sys.modules:
58
+ return _find_spec(name, path)
59
+ else:
60
+ module = sys.modules[name]
61
+ if module is None:
62
+ return None
63
+ try:
64
+ spec = module.__spec__
65
+ except AttributeError:
66
+ raise ValueError('{}.__spec__ is not set'.format(name)) from None
67
+ else:
68
+ if spec is None:
69
+ raise ValueError('{}.__spec__ is None'.format(name))
70
+ return spec
71
+
72
+
73
+ def find_spec(name, package=None):
74
+ """Return the spec for the specified module.
75
+
76
+ First, sys.modules is checked to see if the module was already imported. If
77
+ so, then sys.modules[name].__spec__ is returned. If that happens to be
78
+ set to None, then ValueError is raised. If the module is not in
79
+ sys.modules, then sys.meta_path is searched for a suitable spec with the
80
+ value of 'path' given to the finders. None is returned if no spec could
81
+ be found.
82
+
83
+ If the name is for submodule (contains a dot), the parent module is
84
+ automatically imported.
85
+
86
+ The name and package arguments work the same as importlib.import_module().
87
+ In other words, relative module names (with leading dots) work.
88
+
89
+ """
90
+ fullname = resolve_name(name, package) if name.startswith('.') else name
91
+ if fullname not in sys.modules:
92
+ parent_name = fullname.rpartition('.')[0]
93
+ if parent_name:
94
+ parent = __import__(parent_name, fromlist=['__path__'])
95
+ try:
96
+ parent_path = parent.__path__
97
+ except AttributeError as e:
98
+ raise ModuleNotFoundError(
99
+ f"__path__ attribute not found on {parent_name!r} "
100
+ f"while trying to find {fullname!r}", name=fullname) from e
101
+ else:
102
+ parent_path = None
103
+ return _find_spec(fullname, parent_path)
104
+ else:
105
+ module = sys.modules[fullname]
106
+ if module is None:
107
+ return None
108
+ try:
109
+ spec = module.__spec__
110
+ except AttributeError:
111
+ raise ValueError('{}.__spec__ is not set'.format(name)) from None
112
+ else:
113
+ if spec is None:
114
+ raise ValueError('{}.__spec__ is None'.format(name))
115
+ return spec
116
+
117
+
118
+ @contextmanager
119
+ def _module_to_load(name):
120
+ is_reload = name in sys.modules
121
+
122
+ module = sys.modules.get(name)
123
+ if not is_reload:
124
+ # This must be done before open() is called as the 'io' module
125
+ # implicitly imports 'locale' and would otherwise trigger an
126
+ # infinite loop.
127
+ module = type(sys)(name)
128
+ # This must be done before putting the module in sys.modules
129
+ # (otherwise an optimization shortcut in import.c becomes wrong)
130
+ module.__initializing__ = True
131
+ sys.modules[name] = module
132
+ try:
133
+ yield module
134
+ except Exception:
135
+ if not is_reload:
136
+ try:
137
+ del sys.modules[name]
138
+ except KeyError:
139
+ pass
140
+ finally:
141
+ module.__initializing__ = False
142
+
143
+
144
+ def set_package(fxn):
145
+ """Set __package__ on the returned module.
146
+
147
+ This function is deprecated.
148
+
149
+ """
150
+ @functools.wraps(fxn)
151
+ def set_package_wrapper(*args, **kwargs):
152
+ warnings.warn('The import system now takes care of this automatically; '
153
+ 'this decorator is slated for removal in Python 3.12',
154
+ DeprecationWarning, stacklevel=2)
155
+ module = fxn(*args, **kwargs)
156
+ if getattr(module, '__package__', None) is None:
157
+ module.__package__ = module.__name__
158
+ if not hasattr(module, '__path__'):
159
+ module.__package__ = module.__package__.rpartition('.')[0]
160
+ return module
161
+ return set_package_wrapper
162
+
163
+
164
+ def set_loader(fxn):
165
+ """Set __loader__ on the returned module.
166
+
167
+ This function is deprecated.
168
+
169
+ """
170
+ @functools.wraps(fxn)
171
+ def set_loader_wrapper(self, *args, **kwargs):
172
+ warnings.warn('The import system now takes care of this automatically; '
173
+ 'this decorator is slated for removal in Python 3.12',
174
+ DeprecationWarning, stacklevel=2)
175
+ module = fxn(self, *args, **kwargs)
176
+ if getattr(module, '__loader__', None) is None:
177
+ module.__loader__ = self
178
+ return module
179
+ return set_loader_wrapper
180
+
181
+
182
+ def module_for_loader(fxn):
183
+ """Decorator to handle selecting the proper module for loaders.
184
+
185
+ The decorated function is passed the module to use instead of the module
186
+ name. The module passed in to the function is either from sys.modules if
187
+ it already exists or is a new module. If the module is new, then __name__
188
+ is set the first argument to the method, __loader__ is set to self, and
189
+ __package__ is set accordingly (if self.is_package() is defined) will be set
190
+ before it is passed to the decorated function (if self.is_package() does
191
+ not work for the module it will be set post-load).
192
+
193
+ If an exception is raised and the decorator created the module it is
194
+ subsequently removed from sys.modules.
195
+
196
+ The decorator assumes that the decorated function takes the module name as
197
+ the second argument.
198
+
199
+ """
200
+ warnings.warn('The import system now takes care of this automatically; '
201
+ 'this decorator is slated for removal in Python 3.12',
202
+ DeprecationWarning, stacklevel=2)
203
+ @functools.wraps(fxn)
204
+ def module_for_loader_wrapper(self, fullname, *args, **kwargs):
205
+ with _module_to_load(fullname) as module:
206
+ module.__loader__ = self
207
+ try:
208
+ is_package = self.is_package(fullname)
209
+ except (ImportError, AttributeError):
210
+ pass
211
+ else:
212
+ if is_package:
213
+ module.__package__ = fullname
214
+ else:
215
+ module.__package__ = fullname.rpartition('.')[0]
216
+ # If __package__ was not set above, __import__() will do it later.
217
+ return fxn(self, module, *args, **kwargs)
218
+
219
+ return module_for_loader_wrapper
220
+
221
+
222
+ class _LazyModule(types.ModuleType):
223
+
224
+ """A subclass of the module type which triggers loading upon attribute access."""
225
+
226
+ def __getattribute__(self, attr):
227
+ """Trigger the load of the module and return the attribute."""
228
+ # All module metadata must be garnered from __spec__ in order to avoid
229
+ # using mutated values.
230
+ # Stop triggering this method.
231
+ self.__class__ = types.ModuleType
232
+ # Get the original name to make sure no object substitution occurred
233
+ # in sys.modules.
234
+ original_name = self.__spec__.name
235
+ # Figure out exactly what attributes were mutated between the creation
236
+ # of the module and now.
237
+ attrs_then = self.__spec__.loader_state['__dict__']
238
+ attrs_now = self.__dict__
239
+ attrs_updated = {}
240
+ for key, value in attrs_now.items():
241
+ # Code that set the attribute may have kept a reference to the
242
+ # assigned object, making identity more important than equality.
243
+ if key not in attrs_then:
244
+ attrs_updated[key] = value
245
+ elif id(attrs_now[key]) != id(attrs_then[key]):
246
+ attrs_updated[key] = value
247
+ self.__spec__.loader.exec_module(self)
248
+ # If exec_module() was used directly there is no guarantee the module
249
+ # object was put into sys.modules.
250
+ if original_name in sys.modules:
251
+ if id(self) != id(sys.modules[original_name]):
252
+ raise ValueError(f"module object for {original_name!r} "
253
+ "substituted in sys.modules during a lazy "
254
+ "load")
255
+ # Update after loading since that's what would happen in an eager
256
+ # loading situation.
257
+ self.__dict__.update(attrs_updated)
258
+ return getattr(self, attr)
259
+
260
+ def __delattr__(self, attr):
261
+ """Trigger the load and then perform the deletion."""
262
+ # To trigger the load and raise an exception if the attribute
263
+ # doesn't exist.
264
+ self.__getattribute__(attr)
265
+ delattr(self, attr)
266
+
267
+
268
+ class LazyLoader(Loader):
269
+
270
+ """A loader that creates a module which defers loading until attribute access."""
271
+
272
+ @staticmethod
273
+ def __check_eager_loader(loader):
274
+ if not hasattr(loader, 'exec_module'):
275
+ raise TypeError('loader must define exec_module()')
276
+
277
+ @classmethod
278
+ def factory(cls, loader):
279
+ """Construct a callable which returns the eager loader made lazy."""
280
+ cls.__check_eager_loader(loader)
281
+ return lambda *args, **kwargs: cls(loader(*args, **kwargs))
282
+
283
+ def __init__(self, loader):
284
+ self.__check_eager_loader(loader)
285
+ self.loader = loader
286
+
287
+ def create_module(self, spec):
288
+ return self.loader.create_module(spec)
289
+
290
+ def exec_module(self, module):
291
+ """Make the module load lazily."""
292
+ module.__spec__.loader = self.loader
293
+ module.__loader__ = self.loader
294
+ # Don't need to worry about deep-copying as trying to set an attribute
295
+ # on an object would have triggered the load,
296
+ # e.g. ``module.__spec__.loader = None`` would trigger a load from
297
+ # trying to access module.__spec__.
298
+ loader_state = {}
299
+ loader_state['__dict__'] = module.__dict__.copy()
300
+ loader_state['__class__'] = module.__class__
301
+ module.__spec__.loader_state = loader_state
302
+ module.__class__ = _LazyModule
parrot/lib/python3.10/logging/__pycache__/config.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
parrot/lib/python3.10/logging/config.py ADDED
@@ -0,0 +1,947 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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()
parrot/lib/python3.10/logging/handlers.py ADDED
@@ -0,0 +1,1587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
parrot/lib/python3.10/turtledemo/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ --------------------------------------
3
+ About this viewer
4
+ --------------------------------------
5
+
6
+ Tiny demo viewer to view turtle graphics example scripts.
7
+
8
+ Quickly and dirtyly assembled by Gregor Lingl.
9
+ June, 2006
10
+
11
+ For more information see: turtledemo - Help
12
+
13
+ Have fun!
14
+ """
parrot/lib/python3.10/turtledemo/__main__.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ """
4
+ ----------------------------------------------
5
+ turtleDemo - Help
6
+ ----------------------------------------------
7
+
8
+ This document has two sections:
9
+
10
+ (1) How to use the demo viewer
11
+ (2) How to add your own demos to the demo repository
12
+
13
+
14
+ (1) How to use the demo viewer.
15
+
16
+ Select a demoscript from the example menu.
17
+ The (syntax colored) source code appears in the left
18
+ source code window. IT CANNOT BE EDITED, but ONLY VIEWED!
19
+
20
+ The demo viewer windows can be resized. The divider between text
21
+ and canvas can be moved by grabbing it with the mouse. The text font
22
+ size can be changed from the menu and with Control/Command '-'/'+'.
23
+ It can also be changed on most systems with Control-mousewheel
24
+ when the mouse is over the text.
25
+
26
+ Press START button to start the demo.
27
+ Stop execution by pressing the STOP button.
28
+ Clear screen by pressing the CLEAR button.
29
+ Restart by pressing the START button again.
30
+
31
+ SPECIAL demos, such as clock.py are those which run EVENTDRIVEN.
32
+
33
+ Press START button to start the demo.
34
+
35
+ - Until the EVENTLOOP is entered everything works
36
+ as in an ordinary demo script.
37
+
38
+ - When the EVENTLOOP is entered, you control the
39
+ application by using the mouse and/or keys (or it's
40
+ controlled by some timer events)
41
+ To stop it you can and must press the STOP button.
42
+
43
+ While the EVENTLOOP is running, the examples menu is disabled.
44
+
45
+ - Only after having pressed the STOP button, you may
46
+ restart it or choose another example script.
47
+
48
+ * * * * * * * *
49
+ In some rare situations there may occur interferences/conflicts
50
+ between events concerning the demo script and those concerning the
51
+ demo-viewer. (They run in the same process.) Strange behaviour may be
52
+ the consequence and in the worst case you must close and restart the
53
+ viewer.
54
+ * * * * * * * *
55
+
56
+
57
+ (2) How to add your own demos to the demo repository
58
+
59
+ - Place the file in the same directory as turtledemo/__main__.py
60
+ IMPORTANT! When imported, the demo should not modify the system
61
+ by calling functions in other modules, such as sys, tkinter, or
62
+ turtle. Global variables should be initialized in main().
63
+
64
+ - The code must contain a main() function which will
65
+ be executed by the viewer (see provided example scripts).
66
+ It may return a string which will be displayed in the Label below
67
+ the source code window (when execution has finished.)
68
+
69
+ - In order to run mydemo.py by itself, such as during development,
70
+ add the following at the end of the file:
71
+
72
+ if __name__ == '__main__':
73
+ main()
74
+ mainloop() # keep window open
75
+
76
+ python -m turtledemo.mydemo # will then run it
77
+
78
+ - If the demo is EVENT DRIVEN, main must return the string
79
+ "EVENTLOOP". This informs the demo viewer that the script is
80
+ still running and must be stopped by the user!
81
+
82
+ If an "EVENTLOOP" demo runs by itself, as with clock, which uses
83
+ ontimer, or minimal_hanoi, which loops by recursion, then the
84
+ code should catch the turtle.Terminator exception that will be
85
+ raised when the user presses the STOP button. (Paint is not such
86
+ a demo; it only acts in response to mouse clicks and movements.)
87
+ """
88
+ import sys
89
+ import os
90
+
91
+ from tkinter import *
92
+ from idlelib.colorizer import ColorDelegator, color_config
93
+ from idlelib.percolator import Percolator
94
+ from idlelib.textview import view_text
95
+ from turtledemo import __doc__ as about_turtledemo
96
+
97
+ import turtle
98
+
99
+ demo_dir = os.path.dirname(os.path.abspath(__file__))
100
+ darwin = sys.platform == 'darwin'
101
+
102
+ STARTUP = 1
103
+ READY = 2
104
+ RUNNING = 3
105
+ DONE = 4
106
+ EVENTDRIVEN = 5
107
+
108
+ menufont = ("Arial", 12, NORMAL)
109
+ btnfont = ("Arial", 12, 'bold')
110
+ txtfont = ['Lucida Console', 10, 'normal']
111
+
112
+ MINIMUM_FONT_SIZE = 6
113
+ MAXIMUM_FONT_SIZE = 100
114
+ font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30]
115
+
116
+ def getExampleEntries():
117
+ return [entry[:-3] for entry in os.listdir(demo_dir) if
118
+ entry.endswith(".py") and entry[0] != '_']
119
+
120
+ help_entries = ( # (help_label, help_doc)
121
+ ('Turtledemo help', __doc__),
122
+ ('About turtledemo', about_turtledemo),
123
+ ('About turtle module', turtle.__doc__),
124
+ )
125
+
126
+
127
+ class DemoWindow(object):
128
+
129
+ def __init__(self, filename=None):
130
+ self.root = root = turtle._root = Tk()
131
+ root.title('Python turtle-graphics examples')
132
+ root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
133
+
134
+ if darwin:
135
+ import subprocess
136
+ # Make sure we are the currently activated OS X application
137
+ # so that our menu bar appears.
138
+ subprocess.run(
139
+ [
140
+ 'osascript',
141
+ '-e', 'tell application "System Events"',
142
+ '-e', 'set frontmost of the first process whose '
143
+ 'unix id is {} to true'.format(os.getpid()),
144
+ '-e', 'end tell',
145
+ ],
146
+ stderr=subprocess.DEVNULL,
147
+ stdout=subprocess.DEVNULL,)
148
+
149
+ root.grid_rowconfigure(0, weight=1)
150
+ root.grid_columnconfigure(0, weight=1)
151
+ root.grid_columnconfigure(1, minsize=90, weight=1)
152
+ root.grid_columnconfigure(2, minsize=90, weight=1)
153
+ root.grid_columnconfigure(3, minsize=90, weight=1)
154
+
155
+ self.mBar = Menu(root, relief=RAISED, borderwidth=2)
156
+ self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
157
+ label='Examples', underline=0)
158
+ self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
159
+ label='Fontsize', underline=0)
160
+ self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
161
+ label='Help', underline=0)
162
+ root['menu'] = self.mBar
163
+
164
+ pane = PanedWindow(orient=HORIZONTAL, sashwidth=5,
165
+ sashrelief=SOLID, bg='#ddd')
166
+ pane.add(self.makeTextFrame(pane))
167
+ pane.add(self.makeGraphFrame(pane))
168
+ pane.grid(row=0, columnspan=4, sticky='news')
169
+
170
+ self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf",
171
+ font=("Arial", 16, 'normal'), borderwidth=2,
172
+ relief=RIDGE)
173
+ if darwin: # Leave Mac button colors alone - #44254.
174
+ self.start_btn = Button(root, text=" START ", font=btnfont,
175
+ fg='#00cc22', command=self.startDemo)
176
+ self.stop_btn = Button(root, text=" STOP ", font=btnfont,
177
+ fg='#00cc22', command=self.stopIt)
178
+ self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
179
+ fg='#00cc22', command = self.clearCanvas)
180
+ else:
181
+ self.start_btn = Button(root, text=" START ", font=btnfont,
182
+ fg="white", disabledforeground = "#fed",
183
+ command=self.startDemo)
184
+ self.stop_btn = Button(root, text=" STOP ", font=btnfont,
185
+ fg="white", disabledforeground = "#fed",
186
+ command=self.stopIt)
187
+ self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
188
+ fg="white", disabledforeground="#fed",
189
+ command = self.clearCanvas)
190
+ self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
191
+ self.start_btn.grid(row=1, column=1, sticky='ew')
192
+ self.stop_btn.grid(row=1, column=2, sticky='ew')
193
+ self.clear_btn.grid(row=1, column=3, sticky='ew')
194
+
195
+ Percolator(self.text).insertfilter(ColorDelegator())
196
+ self.dirty = False
197
+ self.exitflag = False
198
+ if filename:
199
+ self.loadfile(filename)
200
+ self.configGUI(DISABLED, DISABLED, DISABLED,
201
+ "Choose example from menu", "black")
202
+ self.state = STARTUP
203
+
204
+
205
+ def onResize(self, event):
206
+ cwidth = self._canvas.winfo_width()
207
+ cheight = self._canvas.winfo_height()
208
+ self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
209
+ self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
210
+
211
+ def makeTextFrame(self, root):
212
+ self.text_frame = text_frame = Frame(root)
213
+ self.text = text = Text(text_frame, name='text', padx=5,
214
+ wrap='none', width=45)
215
+ color_config(text)
216
+
217
+ self.vbar = vbar = Scrollbar(text_frame, name='vbar')
218
+ vbar['command'] = text.yview
219
+ vbar.pack(side=LEFT, fill=Y)
220
+ self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
221
+ hbar['command'] = text.xview
222
+ hbar.pack(side=BOTTOM, fill=X)
223
+ text['yscrollcommand'] = vbar.set
224
+ text['xscrollcommand'] = hbar.set
225
+
226
+ text['font'] = tuple(txtfont)
227
+ shortcut = 'Command' if darwin else 'Control'
228
+ text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
229
+ text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
230
+ text.bind_all('<%s-equal>' % shortcut, self.increase_size)
231
+ text.bind_all('<%s-plus>' % shortcut, self.increase_size)
232
+ text.bind('<Control-MouseWheel>', self.update_mousewheel)
233
+ text.bind('<Control-Button-4>', self.increase_size)
234
+ text.bind('<Control-Button-5>', self.decrease_size)
235
+
236
+ text.pack(side=LEFT, fill=BOTH, expand=1)
237
+ return text_frame
238
+
239
+ def makeGraphFrame(self, root):
240
+ turtle._Screen._root = root
241
+ self.canvwidth = 1000
242
+ self.canvheight = 800
243
+ turtle._Screen._canvas = self._canvas = canvas = turtle.ScrolledCanvas(
244
+ root, 800, 600, self.canvwidth, self.canvheight)
245
+ canvas.adjustScrolls()
246
+ canvas._rootwindow.bind('<Configure>', self.onResize)
247
+ canvas._canvas['borderwidth'] = 0
248
+
249
+ self.screen = _s_ = turtle.Screen()
250
+ turtle.TurtleScreen.__init__(_s_, _s_._canvas)
251
+ self.scanvas = _s_._canvas
252
+ turtle.RawTurtle.screens = [_s_]
253
+ return canvas
254
+
255
+ def set_txtsize(self, size):
256
+ txtfont[1] = size
257
+ self.text['font'] = tuple(txtfont)
258
+ self.output_lbl['text'] = 'Font size %d' % size
259
+
260
+ def decrease_size(self, dummy=None):
261
+ self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
262
+ return 'break'
263
+
264
+ def increase_size(self, dummy=None):
265
+ self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
266
+ return 'break'
267
+
268
+ def update_mousewheel(self, event):
269
+ # For wheel up, event.delta = 120 on Windows, -1 on darwin.
270
+ # X-11 sends Control-Button-4 event instead.
271
+ if (event.delta < 0) == (not darwin):
272
+ return self.decrease_size()
273
+ else:
274
+ return self.increase_size()
275
+
276
+ def configGUI(self, start, stop, clear, txt="", color="blue"):
277
+ if darwin: # Leave Mac button colors alone - #44254.
278
+ self.start_btn.config(state=start)
279
+ self.stop_btn.config(state=stop)
280
+ self.clear_btn.config(state=clear)
281
+ else:
282
+ self.start_btn.config(state=start,
283
+ bg="#d00" if start == NORMAL else "#fca")
284
+ self.stop_btn.config(state=stop,
285
+ bg="#d00" if stop == NORMAL else "#fca")
286
+ self.clear_btn.config(state=clear,
287
+ bg="#d00" if clear == NORMAL else "#fca")
288
+ self.output_lbl.config(text=txt, fg=color)
289
+
290
+ def makeLoadDemoMenu(self, master):
291
+ menu = Menu(master)
292
+
293
+ for entry in getExampleEntries():
294
+ def load(entry=entry):
295
+ self.loadfile(entry)
296
+ menu.add_command(label=entry, underline=0,
297
+ font=menufont, command=load)
298
+ return menu
299
+
300
+ def makeFontMenu(self, master):
301
+ menu = Menu(master)
302
+ menu.add_command(label="Decrease (C-'-')", command=self.decrease_size,
303
+ font=menufont)
304
+ menu.add_command(label="Increase (C-'+')", command=self.increase_size,
305
+ font=menufont)
306
+ menu.add_separator()
307
+
308
+ for size in font_sizes:
309
+ def resize(size=size):
310
+ self.set_txtsize(size)
311
+ menu.add_command(label=str(size), underline=0,
312
+ font=menufont, command=resize)
313
+ return menu
314
+
315
+ def makeHelpMenu(self, master):
316
+ menu = Menu(master)
317
+
318
+ for help_label, help_file in help_entries:
319
+ def show(help_label=help_label, help_file=help_file):
320
+ view_text(self.root, help_label, help_file)
321
+ menu.add_command(label=help_label, font=menufont, command=show)
322
+ return menu
323
+
324
+ def refreshCanvas(self):
325
+ if self.dirty:
326
+ self.screen.clear()
327
+ self.dirty=False
328
+
329
+ def loadfile(self, filename):
330
+ self.clearCanvas()
331
+ turtle.TurtleScreen._RUNNING = False
332
+ modname = 'turtledemo.' + filename
333
+ __import__(modname)
334
+ self.module = sys.modules[modname]
335
+ with open(self.module.__file__, 'r') as f:
336
+ chars = f.read()
337
+ self.text.delete("1.0", "end")
338
+ self.text.insert("1.0", chars)
339
+ self.root.title(filename + " - a Python turtle graphics example")
340
+ self.configGUI(NORMAL, DISABLED, DISABLED,
341
+ "Press start button", "red")
342
+ self.state = READY
343
+
344
+ def startDemo(self):
345
+ self.refreshCanvas()
346
+ self.dirty = True
347
+ turtle.TurtleScreen._RUNNING = True
348
+ self.configGUI(DISABLED, NORMAL, DISABLED,
349
+ "demo running...", "black")
350
+ self.screen.clear()
351
+ self.screen.mode("standard")
352
+ self.state = RUNNING
353
+
354
+ try:
355
+ result = self.module.main()
356
+ if result == "EVENTLOOP":
357
+ self.state = EVENTDRIVEN
358
+ else:
359
+ self.state = DONE
360
+ except turtle.Terminator:
361
+ if self.root is None:
362
+ return
363
+ self.state = DONE
364
+ result = "stopped!"
365
+ if self.state == DONE:
366
+ self.configGUI(NORMAL, DISABLED, NORMAL,
367
+ result)
368
+ elif self.state == EVENTDRIVEN:
369
+ self.exitflag = True
370
+ self.configGUI(DISABLED, NORMAL, DISABLED,
371
+ "use mouse/keys or STOP", "red")
372
+
373
+ def clearCanvas(self):
374
+ self.refreshCanvas()
375
+ self.screen._delete("all")
376
+ self.scanvas.config(cursor="")
377
+ self.configGUI(NORMAL, DISABLED, DISABLED)
378
+
379
+ def stopIt(self):
380
+ if self.exitflag:
381
+ self.clearCanvas()
382
+ self.exitflag = False
383
+ self.configGUI(NORMAL, DISABLED, DISABLED,
384
+ "STOPPED!", "red")
385
+ turtle.TurtleScreen._RUNNING = False
386
+
387
+ def _destroy(self):
388
+ turtle.TurtleScreen._RUNNING = False
389
+ self.root.destroy()
390
+ self.root = None
391
+
392
+
393
+ def main():
394
+ demo = DemoWindow()
395
+ demo.root.mainloop()
396
+
397
+ if __name__ == '__main__':
398
+ main()
parrot/lib/python3.10/turtledemo/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/bytedesign.cpython-310.pyc ADDED
Binary file (4.08 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/chaos.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/clock.cpython-310.pyc ADDED
Binary file (3.69 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/colormixer.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/forest.cpython-310.pyc ADDED
Binary file (3.54 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/fractalcurves.cpython-310.pyc ADDED
Binary file (3.15 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/lindenmayer.cpython-310.pyc ADDED
Binary file (2.79 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/minimal_hanoi.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/nim.cpython-310.pyc ADDED
Binary file (7.66 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/paint.cpython-310.pyc ADDED
Binary file (1.62 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/peace.cpython-310.pyc ADDED
Binary file (1.38 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/planet_and_moon.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/rosette.cpython-310.pyc ADDED
Binary file (1.73 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/round_dance.cpython-310.pyc ADDED
Binary file (1.9 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/sorting_animate.cpython-310.pyc ADDED
Binary file (6.33 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/tree.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/two_canvases.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
parrot/lib/python3.10/turtledemo/__pycache__/yinyang.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
parrot/lib/python3.10/turtledemo/bytedesign.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_bytedesign.py
5
+
6
+ An example adapted from the example-suite
7
+ of PythonCard's turtle graphics.
8
+
9
+ It's based on an article in BYTE magazine
10
+ Problem Solving with Logo: Using Turtle
11
+ Graphics to Redraw a Design
12
+ November 1982, p. 118 - 134
13
+
14
+ -------------------------------------------
15
+
16
+ Due to the statement
17
+
18
+ t.delay(0)
19
+
20
+ in line 152, which sets the animation delay
21
+ to 0, this animation runs in "line per line"
22
+ mode as fast as possible.
23
+ """
24
+
25
+ from turtle import Turtle, mainloop
26
+ from time import perf_counter as clock
27
+
28
+ # wrapper for any additional drawing routines
29
+ # that need to know about each other
30
+ class Designer(Turtle):
31
+
32
+ def design(self, homePos, scale):
33
+ self.up()
34
+ for i in range(5):
35
+ self.forward(64.65 * scale)
36
+ self.down()
37
+ self.wheel(self.position(), scale)
38
+ self.up()
39
+ self.backward(64.65 * scale)
40
+ self.right(72)
41
+ self.up()
42
+ self.goto(homePos)
43
+ self.right(36)
44
+ self.forward(24.5 * scale)
45
+ self.right(198)
46
+ self.down()
47
+ self.centerpiece(46 * scale, 143.4, scale)
48
+ self.getscreen().tracer(True)
49
+
50
+ def wheel(self, initpos, scale):
51
+ self.right(54)
52
+ for i in range(4):
53
+ self.pentpiece(initpos, scale)
54
+ self.down()
55
+ self.left(36)
56
+ for i in range(5):
57
+ self.tripiece(initpos, scale)
58
+ self.left(36)
59
+ for i in range(5):
60
+ self.down()
61
+ self.right(72)
62
+ self.forward(28 * scale)
63
+ self.up()
64
+ self.backward(28 * scale)
65
+ self.left(54)
66
+ self.getscreen().update()
67
+
68
+ def tripiece(self, initpos, scale):
69
+ oldh = self.heading()
70
+ self.down()
71
+ self.backward(2.5 * scale)
72
+ self.tripolyr(31.5 * scale, scale)
73
+ self.up()
74
+ self.goto(initpos)
75
+ self.setheading(oldh)
76
+ self.down()
77
+ self.backward(2.5 * scale)
78
+ self.tripolyl(31.5 * scale, scale)
79
+ self.up()
80
+ self.goto(initpos)
81
+ self.setheading(oldh)
82
+ self.left(72)
83
+ self.getscreen().update()
84
+
85
+ def pentpiece(self, initpos, scale):
86
+ oldh = self.heading()
87
+ self.up()
88
+ self.forward(29 * scale)
89
+ self.down()
90
+ for i in range(5):
91
+ self.forward(18 * scale)
92
+ self.right(72)
93
+ self.pentr(18 * scale, 75, scale)
94
+ self.up()
95
+ self.goto(initpos)
96
+ self.setheading(oldh)
97
+ self.forward(29 * scale)
98
+ self.down()
99
+ for i in range(5):
100
+ self.forward(18 * scale)
101
+ self.right(72)
102
+ self.pentl(18 * scale, 75, scale)
103
+ self.up()
104
+ self.goto(initpos)
105
+ self.setheading(oldh)
106
+ self.left(72)
107
+ self.getscreen().update()
108
+
109
+ def pentl(self, side, ang, scale):
110
+ if side < (2 * scale): return
111
+ self.forward(side)
112
+ self.left(ang)
113
+ self.pentl(side - (.38 * scale), ang, scale)
114
+
115
+ def pentr(self, side, ang, scale):
116
+ if side < (2 * scale): return
117
+ self.forward(side)
118
+ self.right(ang)
119
+ self.pentr(side - (.38 * scale), ang, scale)
120
+
121
+ def tripolyr(self, side, scale):
122
+ if side < (4 * scale): return
123
+ self.forward(side)
124
+ self.right(111)
125
+ self.forward(side / 1.78)
126
+ self.right(111)
127
+ self.forward(side / 1.3)
128
+ self.right(146)
129
+ self.tripolyr(side * .75, scale)
130
+
131
+ def tripolyl(self, side, scale):
132
+ if side < (4 * scale): return
133
+ self.forward(side)
134
+ self.left(111)
135
+ self.forward(side / 1.78)
136
+ self.left(111)
137
+ self.forward(side / 1.3)
138
+ self.left(146)
139
+ self.tripolyl(side * .75, scale)
140
+
141
+ def centerpiece(self, s, a, scale):
142
+ self.forward(s); self.left(a)
143
+ if s < (7.5 * scale):
144
+ return
145
+ self.centerpiece(s - (1.2 * scale), a, scale)
146
+
147
+ def main():
148
+ t = Designer()
149
+ t.speed(0)
150
+ t.hideturtle()
151
+ t.getscreen().delay(0)
152
+ t.getscreen().tracer(0)
153
+ at = clock()
154
+ t.design(t.position(), 2)
155
+ et = clock()
156
+ return "runtime: %.2f sec." % (et-at)
157
+
158
+ if __name__ == '__main__':
159
+ msg = main()
160
+ print(msg)
161
+ mainloop()
parrot/lib/python3.10/turtledemo/chaos.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File: tdemo_chaos.py
2
+ # Author: Gregor Lingl
3
+ # Date: 2009-06-24
4
+
5
+ # A demonstration of chaos
6
+
7
+ from turtle import *
8
+
9
+ N = 80
10
+
11
+ def f(x):
12
+ return 3.9*x*(1-x)
13
+
14
+ def g(x):
15
+ return 3.9*(x-x**2)
16
+
17
+ def h(x):
18
+ return 3.9*x-3.9*x*x
19
+
20
+ def jumpto(x, y):
21
+ penup(); goto(x,y)
22
+
23
+ def line(x1, y1, x2, y2):
24
+ jumpto(x1, y1)
25
+ pendown()
26
+ goto(x2, y2)
27
+
28
+ def coosys():
29
+ line(-1, 0, N+1, 0)
30
+ line(0, -0.1, 0, 1.1)
31
+
32
+ def plot(fun, start, color):
33
+ pencolor(color)
34
+ x = start
35
+ jumpto(0, x)
36
+ pendown()
37
+ dot(5)
38
+ for i in range(N):
39
+ x=fun(x)
40
+ goto(i+1,x)
41
+ dot(5)
42
+
43
+ def main():
44
+ reset()
45
+ setworldcoordinates(-1.0,-0.1, N+1, 1.1)
46
+ speed(0)
47
+ hideturtle()
48
+ coosys()
49
+ plot(f, 0.35, "blue")
50
+ plot(g, 0.35, "green")
51
+ plot(h, 0.35, "red")
52
+ # Now zoom in:
53
+ for s in range(100):
54
+ setworldcoordinates(0.5*s,-0.1, N+1, 1.1)
55
+ return "Done!"
56
+
57
+ if __name__ == "__main__":
58
+ main()
59
+ mainloop()
parrot/lib/python3.10/turtledemo/clock.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: cp1252 -*-
3
+ """ turtle-example-suite:
4
+
5
+ tdemo_clock.py
6
+
7
+ Enhanced clock-program, showing date
8
+ and time
9
+ ------------------------------------
10
+ Press STOP to exit the program!
11
+ ------------------------------------
12
+ """
13
+ from turtle import *
14
+ from datetime import datetime
15
+
16
+ def jump(distanz, winkel=0):
17
+ penup()
18
+ right(winkel)
19
+ forward(distanz)
20
+ left(winkel)
21
+ pendown()
22
+
23
+ def hand(laenge, spitze):
24
+ fd(laenge*1.15)
25
+ rt(90)
26
+ fd(spitze/2.0)
27
+ lt(120)
28
+ fd(spitze)
29
+ lt(120)
30
+ fd(spitze)
31
+ lt(120)
32
+ fd(spitze/2.0)
33
+
34
+ def make_hand_shape(name, laenge, spitze):
35
+ reset()
36
+ jump(-laenge*0.15)
37
+ begin_poly()
38
+ hand(laenge, spitze)
39
+ end_poly()
40
+ hand_form = get_poly()
41
+ register_shape(name, hand_form)
42
+
43
+ def clockface(radius):
44
+ reset()
45
+ pensize(7)
46
+ for i in range(60):
47
+ jump(radius)
48
+ if i % 5 == 0:
49
+ fd(25)
50
+ jump(-radius-25)
51
+ else:
52
+ dot(3)
53
+ jump(-radius)
54
+ rt(6)
55
+
56
+ def setup():
57
+ global second_hand, minute_hand, hour_hand, writer
58
+ mode("logo")
59
+ make_hand_shape("second_hand", 125, 25)
60
+ make_hand_shape("minute_hand", 130, 25)
61
+ make_hand_shape("hour_hand", 90, 25)
62
+ clockface(160)
63
+ second_hand = Turtle()
64
+ second_hand.shape("second_hand")
65
+ second_hand.color("gray20", "gray80")
66
+ minute_hand = Turtle()
67
+ minute_hand.shape("minute_hand")
68
+ minute_hand.color("blue1", "red1")
69
+ hour_hand = Turtle()
70
+ hour_hand.shape("hour_hand")
71
+ hour_hand.color("blue3", "red3")
72
+ for hand in second_hand, minute_hand, hour_hand:
73
+ hand.resizemode("user")
74
+ hand.shapesize(1, 1, 3)
75
+ hand.speed(0)
76
+ ht()
77
+ writer = Turtle()
78
+ #writer.mode("logo")
79
+ writer.ht()
80
+ writer.pu()
81
+ writer.bk(85)
82
+
83
+ def wochentag(t):
84
+ wochentag = ["Monday", "Tuesday", "Wednesday",
85
+ "Thursday", "Friday", "Saturday", "Sunday"]
86
+ return wochentag[t.weekday()]
87
+
88
+ def datum(z):
89
+ monat = ["Jan.", "Feb.", "Mar.", "Apr.", "May", "June",
90
+ "July", "Aug.", "Sep.", "Oct.", "Nov.", "Dec."]
91
+ j = z.year
92
+ m = monat[z.month - 1]
93
+ t = z.day
94
+ return "%s %d %d" % (m, t, j)
95
+
96
+ def tick():
97
+ t = datetime.today()
98
+ sekunde = t.second + t.microsecond*0.000001
99
+ minute = t.minute + sekunde/60.0
100
+ stunde = t.hour + minute/60.0
101
+ try:
102
+ tracer(False) # Terminator can occur here
103
+ writer.clear()
104
+ writer.home()
105
+ writer.forward(65)
106
+ writer.write(wochentag(t),
107
+ align="center", font=("Courier", 14, "bold"))
108
+ writer.back(150)
109
+ writer.write(datum(t),
110
+ align="center", font=("Courier", 14, "bold"))
111
+ writer.forward(85)
112
+ second_hand.setheading(6*sekunde) # or here
113
+ minute_hand.setheading(6*minute)
114
+ hour_hand.setheading(30*stunde)
115
+ tracer(True)
116
+ ontimer(tick, 100)
117
+ except Terminator:
118
+ pass # turtledemo user pressed STOP
119
+
120
+ def main():
121
+ tracer(False)
122
+ setup()
123
+ tracer(True)
124
+ tick()
125
+ return "EVENTLOOP"
126
+
127
+ if __name__ == "__main__":
128
+ mode("logo")
129
+ msg = main()
130
+ print(msg)
131
+ mainloop()
parrot/lib/python3.10/turtledemo/colormixer.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # colormixer
2
+
3
+ from turtle import Screen, Turtle, mainloop
4
+
5
+ class ColorTurtle(Turtle):
6
+
7
+ def __init__(self, x, y):
8
+ Turtle.__init__(self)
9
+ self.shape("turtle")
10
+ self.resizemode("user")
11
+ self.shapesize(3,3,5)
12
+ self.pensize(10)
13
+ self._color = [0,0,0]
14
+ self.x = x
15
+ self._color[x] = y
16
+ self.color(self._color)
17
+ self.speed(0)
18
+ self.left(90)
19
+ self.pu()
20
+ self.goto(x,0)
21
+ self.pd()
22
+ self.sety(1)
23
+ self.pu()
24
+ self.sety(y)
25
+ self.pencolor("gray25")
26
+ self.ondrag(self.shift)
27
+
28
+ def shift(self, x, y):
29
+ self.sety(max(0,min(y,1)))
30
+ self._color[self.x] = self.ycor()
31
+ self.fillcolor(self._color)
32
+ setbgcolor()
33
+
34
+ def setbgcolor():
35
+ screen.bgcolor(red.ycor(), green.ycor(), blue.ycor())
36
+
37
+ def main():
38
+ global screen, red, green, blue
39
+ screen = Screen()
40
+ screen.delay(0)
41
+ screen.setworldcoordinates(-1, -0.3, 3, 1.3)
42
+
43
+ red = ColorTurtle(0, .5)
44
+ green = ColorTurtle(1, .5)
45
+ blue = ColorTurtle(2, .5)
46
+ setbgcolor()
47
+
48
+ writer = Turtle()
49
+ writer.ht()
50
+ writer.pu()
51
+ writer.goto(1,1.15)
52
+ writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
53
+ return "EVENTLOOP"
54
+
55
+ if __name__ == "__main__":
56
+ msg = main()
57
+ print(msg)
58
+ mainloop()
parrot/lib/python3.10/turtledemo/forest.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtlegraphics-example-suite:
3
+
4
+ tdemo_forest.py
5
+
6
+ Displays a 'forest' of 3 breadth-first-trees
7
+ similar to the one in tree.
8
+ For further remarks see tree.py
9
+
10
+ This example is a 'breadth-first'-rewrite of
11
+ a Logo program written by Erich Neuwirth. See
12
+ http://homepage.univie.ac.at/erich.neuwirth/
13
+ """
14
+ from turtle import Turtle, colormode, tracer, mainloop
15
+ from random import randrange
16
+ from time import perf_counter as clock
17
+
18
+ def symRandom(n):
19
+ return randrange(-n,n+1)
20
+
21
+ def randomize( branchlist, angledist, sizedist ):
22
+ return [ (angle+symRandom(angledist),
23
+ sizefactor*1.01**symRandom(sizedist))
24
+ for angle, sizefactor in branchlist ]
25
+
26
+ def randomfd( t, distance, parts, angledist ):
27
+ for i in range(parts):
28
+ t.left(symRandom(angledist))
29
+ t.forward( (1.0 * distance)/parts )
30
+
31
+ def tree(tlist, size, level, widthfactor, branchlists, angledist=10, sizedist=5):
32
+ # benutzt Liste von turtles und Liste von Zweiglisten,
33
+ # fuer jede turtle eine!
34
+ if level > 0:
35
+ lst = []
36
+ brs = []
37
+ for t, branchlist in list(zip(tlist,branchlists)):
38
+ t.pensize( size * widthfactor )
39
+ t.pencolor( 255 - (180 - 11 * level + symRandom(15)),
40
+ 180 - 11 * level + symRandom(15),
41
+ 0 )
42
+ t.pendown()
43
+ randomfd(t, size, level, angledist )
44
+ yield 1
45
+ for angle, sizefactor in branchlist:
46
+ t.left(angle)
47
+ lst.append(t.clone())
48
+ brs.append(randomize(branchlist, angledist, sizedist))
49
+ t.right(angle)
50
+ for x in tree(lst, size*sizefactor, level-1, widthfactor, brs,
51
+ angledist, sizedist):
52
+ yield None
53
+
54
+
55
+ def start(t,x,y):
56
+ colormode(255)
57
+ t.reset()
58
+ t.speed(0)
59
+ t.hideturtle()
60
+ t.left(90)
61
+ t.penup()
62
+ t.setpos(x,y)
63
+ t.pendown()
64
+
65
+ def doit1(level, pen):
66
+ pen.hideturtle()
67
+ start(pen, 20, -208)
68
+ t = tree( [pen], 80, level, 0.1, [[ (45,0.69), (0,0.65), (-45,0.71) ]] )
69
+ return t
70
+
71
+ def doit2(level, pen):
72
+ pen.hideturtle()
73
+ start(pen, -135, -130)
74
+ t = tree( [pen], 120, level, 0.1, [[ (45,0.69), (-45,0.71) ]] )
75
+ return t
76
+
77
+ def doit3(level, pen):
78
+ pen.hideturtle()
79
+ start(pen, 190, -90)
80
+ t = tree( [pen], 100, level, 0.1, [[ (45,0.7), (0,0.72), (-45,0.65) ]] )
81
+ return t
82
+
83
+ # Hier 3 Baumgeneratoren:
84
+ def main():
85
+ p = Turtle()
86
+ p.ht()
87
+ tracer(75,0)
88
+ u = doit1(6, Turtle(undobuffersize=1))
89
+ s = doit2(7, Turtle(undobuffersize=1))
90
+ t = doit3(5, Turtle(undobuffersize=1))
91
+ a = clock()
92
+ while True:
93
+ done = 0
94
+ for b in u,s,t:
95
+ try:
96
+ b.__next__()
97
+ except:
98
+ done += 1
99
+ if done == 3:
100
+ break
101
+
102
+ tracer(1,10)
103
+ b = clock()
104
+ return "runtime: %.2f sec." % (b-a)
105
+
106
+ if __name__ == '__main__':
107
+ main()
108
+ mainloop()
parrot/lib/python3.10/turtledemo/fractalcurves.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_fractalCurves.py
5
+
6
+ This program draws two fractal-curve-designs:
7
+ (1) A hilbert curve (in a box)
8
+ (2) A combination of Koch-curves.
9
+
10
+ The CurvesTurtle class and the fractal-curve-
11
+ methods are taken from the PythonCard example
12
+ scripts for turtle-graphics.
13
+ """
14
+ from turtle import *
15
+ from time import sleep, perf_counter as clock
16
+
17
+ class CurvesTurtle(Pen):
18
+ # example derived from
19
+ # Turtle Geometry: The Computer as a Medium for Exploring Mathematics
20
+ # by Harold Abelson and Andrea diSessa
21
+ # p. 96-98
22
+ def hilbert(self, size, level, parity):
23
+ if level == 0:
24
+ return
25
+ # rotate and draw first subcurve with opposite parity to big curve
26
+ self.left(parity * 90)
27
+ self.hilbert(size, level - 1, -parity)
28
+ # interface to and draw second subcurve with same parity as big curve
29
+ self.forward(size)
30
+ self.right(parity * 90)
31
+ self.hilbert(size, level - 1, parity)
32
+ # third subcurve
33
+ self.forward(size)
34
+ self.hilbert(size, level - 1, parity)
35
+ # fourth subcurve
36
+ self.right(parity * 90)
37
+ self.forward(size)
38
+ self.hilbert(size, level - 1, -parity)
39
+ # a final turn is needed to make the turtle
40
+ # end up facing outward from the large square
41
+ self.left(parity * 90)
42
+
43
+ # Visual Modeling with Logo: A Structural Approach to Seeing
44
+ # by James Clayson
45
+ # Koch curve, after Helge von Koch who introduced this geometric figure in 1904
46
+ # p. 146
47
+ def fractalgon(self, n, rad, lev, dir):
48
+ import math
49
+
50
+ # if dir = 1 turn outward
51
+ # if dir = -1 turn inward
52
+ edge = 2 * rad * math.sin(math.pi / n)
53
+ self.pu()
54
+ self.fd(rad)
55
+ self.pd()
56
+ self.rt(180 - (90 * (n - 2) / n))
57
+ for i in range(n):
58
+ self.fractal(edge, lev, dir)
59
+ self.rt(360 / n)
60
+ self.lt(180 - (90 * (n - 2) / n))
61
+ self.pu()
62
+ self.bk(rad)
63
+ self.pd()
64
+
65
+ # p. 146
66
+ def fractal(self, dist, depth, dir):
67
+ if depth < 1:
68
+ self.fd(dist)
69
+ return
70
+ self.fractal(dist / 3, depth - 1, dir)
71
+ self.lt(60 * dir)
72
+ self.fractal(dist / 3, depth - 1, dir)
73
+ self.rt(120 * dir)
74
+ self.fractal(dist / 3, depth - 1, dir)
75
+ self.lt(60 * dir)
76
+ self.fractal(dist / 3, depth - 1, dir)
77
+
78
+ def main():
79
+ ft = CurvesTurtle()
80
+
81
+ ft.reset()
82
+ ft.speed(0)
83
+ ft.ht()
84
+ ft.getscreen().tracer(1,0)
85
+ ft.pu()
86
+
87
+ size = 6
88
+ ft.setpos(-33*size, -32*size)
89
+ ft.pd()
90
+
91
+ ta=clock()
92
+ ft.fillcolor("red")
93
+ ft.begin_fill()
94
+ ft.fd(size)
95
+
96
+ ft.hilbert(size, 6, 1)
97
+
98
+ # frame
99
+ ft.fd(size)
100
+ for i in range(3):
101
+ ft.lt(90)
102
+ ft.fd(size*(64+i%2))
103
+ ft.pu()
104
+ for i in range(2):
105
+ ft.fd(size)
106
+ ft.rt(90)
107
+ ft.pd()
108
+ for i in range(4):
109
+ ft.fd(size*(66+i%2))
110
+ ft.rt(90)
111
+ ft.end_fill()
112
+ tb=clock()
113
+ res = "Hilbert: %.2fsec. " % (tb-ta)
114
+
115
+ sleep(3)
116
+
117
+ ft.reset()
118
+ ft.speed(0)
119
+ ft.ht()
120
+ ft.getscreen().tracer(1,0)
121
+
122
+ ta=clock()
123
+ ft.color("black", "blue")
124
+ ft.begin_fill()
125
+ ft.fractalgon(3, 250, 4, 1)
126
+ ft.end_fill()
127
+ ft.begin_fill()
128
+ ft.color("red")
129
+ ft.fractalgon(3, 200, 4, -1)
130
+ ft.end_fill()
131
+ tb=clock()
132
+ res += "Koch: %.2fsec." % (tb-ta)
133
+ return res
134
+
135
+ if __name__ == '__main__':
136
+ msg = main()
137
+ print(msg)
138
+ mainloop()
parrot/lib/python3.10/turtledemo/lindenmayer.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ xtx_lindenmayer_indian.py
5
+
6
+ Each morning women in Tamil Nadu, in southern
7
+ India, place designs, created by using rice
8
+ flour and known as kolam on the thresholds of
9
+ their homes.
10
+
11
+ These can be described by Lindenmayer systems,
12
+ which can easily be implemented with turtle
13
+ graphics and Python.
14
+
15
+ Two examples are shown here:
16
+ (1) the snake kolam
17
+ (2) anklets of Krishna
18
+
19
+ Taken from Marcia Ascher: Mathematics
20
+ Elsewhere, An Exploration of Ideas Across
21
+ Cultures
22
+
23
+ """
24
+ ################################
25
+ # Mini Lindenmayer tool
26
+ ###############################
27
+
28
+ from turtle import *
29
+
30
+ def replace( seq, replacementRules, n ):
31
+ for i in range(n):
32
+ newseq = ""
33
+ for element in seq:
34
+ newseq = newseq + replacementRules.get(element,element)
35
+ seq = newseq
36
+ return seq
37
+
38
+ def draw( commands, rules ):
39
+ for b in commands:
40
+ try:
41
+ rules[b]()
42
+ except TypeError:
43
+ try:
44
+ draw(rules[b], rules)
45
+ except:
46
+ pass
47
+
48
+
49
+ def main():
50
+ ################################
51
+ # Example 1: Snake kolam
52
+ ################################
53
+
54
+
55
+ def r():
56
+ right(45)
57
+
58
+ def l():
59
+ left(45)
60
+
61
+ def f():
62
+ forward(7.5)
63
+
64
+ snake_rules = {"-":r, "+":l, "f":f, "b":"f+f+f--f--f+f+f"}
65
+ snake_replacementRules = {"b": "b+f+b--f--b+f+b"}
66
+ snake_start = "b--f--b--f"
67
+
68
+ drawing = replace(snake_start, snake_replacementRules, 3)
69
+
70
+ reset()
71
+ speed(3)
72
+ tracer(1,0)
73
+ ht()
74
+ up()
75
+ backward(195)
76
+ down()
77
+ draw(drawing, snake_rules)
78
+
79
+ from time import sleep
80
+ sleep(3)
81
+
82
+ ################################
83
+ # Example 2: Anklets of Krishna
84
+ ################################
85
+
86
+ def A():
87
+ color("red")
88
+ circle(10,90)
89
+
90
+ def B():
91
+ from math import sqrt
92
+ color("black")
93
+ l = 5/sqrt(2)
94
+ forward(l)
95
+ circle(l, 270)
96
+ forward(l)
97
+
98
+ def F():
99
+ color("green")
100
+ forward(10)
101
+
102
+ krishna_rules = {"a":A, "b":B, "f":F}
103
+ krishna_replacementRules = {"a" : "afbfa", "b" : "afbfbfbfa" }
104
+ krishna_start = "fbfbfbfb"
105
+
106
+ reset()
107
+ speed(0)
108
+ tracer(3,0)
109
+ ht()
110
+ left(45)
111
+ drawing = replace(krishna_start, krishna_replacementRules, 3)
112
+ draw(drawing, krishna_rules)
113
+ tracer(1)
114
+ return "Done!"
115
+
116
+ if __name__=='__main__':
117
+ msg = main()
118
+ print(msg)
119
+ mainloop()
parrot/lib/python3.10/turtledemo/minimal_hanoi.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_minimal_hanoi.py
5
+
6
+ A minimal 'Towers of Hanoi' animation:
7
+ A tower of 6 discs is transferred from the
8
+ left to the right peg.
9
+
10
+ An imho quite elegant and concise
11
+ implementation using a tower class, which
12
+ is derived from the built-in type list.
13
+
14
+ Discs are turtles with shape "square", but
15
+ stretched to rectangles by shapesize()
16
+ ---------------------------------------
17
+ To exit press STOP button
18
+ ---------------------------------------
19
+ """
20
+ from turtle import *
21
+
22
+ class Disc(Turtle):
23
+ def __init__(self, n):
24
+ Turtle.__init__(self, shape="square", visible=False)
25
+ self.pu()
26
+ self.shapesize(1.5, n*1.5, 2) # square-->rectangle
27
+ self.fillcolor(n/6., 0, 1-n/6.)
28
+ self.st()
29
+
30
+ class Tower(list):
31
+ "Hanoi tower, a subclass of built-in type list"
32
+ def __init__(self, x):
33
+ "create an empty tower. x is x-position of peg"
34
+ self.x = x
35
+ def push(self, d):
36
+ d.setx(self.x)
37
+ d.sety(-150+34*len(self))
38
+ self.append(d)
39
+ def pop(self):
40
+ d = list.pop(self)
41
+ d.sety(150)
42
+ return d
43
+
44
+ def hanoi(n, from_, with_, to_):
45
+ if n > 0:
46
+ hanoi(n-1, from_, to_, with_)
47
+ to_.push(from_.pop())
48
+ hanoi(n-1, with_, from_, to_)
49
+
50
+ def play():
51
+ onkey(None,"space")
52
+ clear()
53
+ try:
54
+ hanoi(6, t1, t2, t3)
55
+ write("press STOP button to exit",
56
+ align="center", font=("Courier", 16, "bold"))
57
+ except Terminator:
58
+ pass # turtledemo user pressed STOP
59
+
60
+ def main():
61
+ global t1, t2, t3
62
+ ht(); penup(); goto(0, -225) # writer turtle
63
+ t1 = Tower(-250)
64
+ t2 = Tower(0)
65
+ t3 = Tower(250)
66
+ # make tower of 6 discs
67
+ for i in range(6,0,-1):
68
+ t1.push(Disc(i))
69
+ # prepare spartanic user interface ;-)
70
+ write("press spacebar to start game",
71
+ align="center", font=("Courier", 16, "bold"))
72
+ onkey(play, "space")
73
+ listen()
74
+ return "EVENTLOOP"
75
+
76
+ if __name__=="__main__":
77
+ msg = main()
78
+ print(msg)
79
+ mainloop()
parrot/lib/python3.10/turtledemo/nim.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_nim.py
4
+
5
+ Play nim against the computer. The player
6
+ who takes the last stick is the winner.
7
+
8
+ Implements the model-view-controller
9
+ design pattern.
10
+ """
11
+
12
+
13
+ import turtle
14
+ import random
15
+ import time
16
+
17
+ SCREENWIDTH = 640
18
+ SCREENHEIGHT = 480
19
+
20
+ MINSTICKS = 7
21
+ MAXSTICKS = 31
22
+
23
+ HUNIT = SCREENHEIGHT // 12
24
+ WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2)
25
+
26
+ SCOLOR = (63, 63, 31)
27
+ HCOLOR = (255, 204, 204)
28
+ COLOR = (204, 204, 255)
29
+
30
+ def randomrow():
31
+ return random.randint(MINSTICKS, MAXSTICKS)
32
+
33
+ def computerzug(state):
34
+ xored = state[0] ^ state[1] ^ state[2]
35
+ if xored == 0:
36
+ return randommove(state)
37
+ for z in range(3):
38
+ s = state[z] ^ xored
39
+ if s <= state[z]:
40
+ move = (z, s)
41
+ return move
42
+
43
+ def randommove(state):
44
+ m = max(state)
45
+ while True:
46
+ z = random.randint(0,2)
47
+ if state[z] > (m > 1):
48
+ break
49
+ rand = random.randint(m > 1, state[z]-1)
50
+ return z, rand
51
+
52
+
53
+ class NimModel(object):
54
+ def __init__(self, game):
55
+ self.game = game
56
+
57
+ def setup(self):
58
+ if self.game.state not in [Nim.CREATED, Nim.OVER]:
59
+ return
60
+ self.sticks = [randomrow(), randomrow(), randomrow()]
61
+ self.player = 0
62
+ self.winner = None
63
+ self.game.view.setup()
64
+ self.game.state = Nim.RUNNING
65
+
66
+ def move(self, row, col):
67
+ maxspalte = self.sticks[row]
68
+ self.sticks[row] = col
69
+ self.game.view.notify_move(row, col, maxspalte, self.player)
70
+ if self.game_over():
71
+ self.game.state = Nim.OVER
72
+ self.winner = self.player
73
+ self.game.view.notify_over()
74
+ elif self.player == 0:
75
+ self.player = 1
76
+ row, col = computerzug(self.sticks)
77
+ self.move(row, col)
78
+ self.player = 0
79
+
80
+ def game_over(self):
81
+ return self.sticks == [0, 0, 0]
82
+
83
+ def notify_move(self, row, col):
84
+ if self.sticks[row] <= col:
85
+ return
86
+ self.move(row, col)
87
+
88
+
89
+ class Stick(turtle.Turtle):
90
+ def __init__(self, row, col, game):
91
+ turtle.Turtle.__init__(self, visible=False)
92
+ self.row = row
93
+ self.col = col
94
+ self.game = game
95
+ x, y = self.coords(row, col)
96
+ self.shape("square")
97
+ self.shapesize(HUNIT/10.0, WUNIT/20.0)
98
+ self.speed(0)
99
+ self.pu()
100
+ self.goto(x,y)
101
+ self.color("white")
102
+ self.showturtle()
103
+
104
+ def coords(self, row, col):
105
+ packet, remainder = divmod(col, 5)
106
+ x = (3 + 11 * packet + 2 * remainder) * WUNIT
107
+ y = (2 + 3 * row) * HUNIT
108
+ return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2
109
+
110
+ def makemove(self, x, y):
111
+ if self.game.state != Nim.RUNNING:
112
+ return
113
+ self.game.controller.notify_move(self.row, self.col)
114
+
115
+
116
+ class NimView(object):
117
+ def __init__(self, game):
118
+ self.game = game
119
+ self.screen = game.screen
120
+ self.model = game.model
121
+ self.screen.colormode(255)
122
+ self.screen.tracer(False)
123
+ self.screen.bgcolor((240, 240, 255))
124
+ self.writer = turtle.Turtle(visible=False)
125
+ self.writer.pu()
126
+ self.writer.speed(0)
127
+ self.sticks = {}
128
+ for row in range(3):
129
+ for col in range(MAXSTICKS):
130
+ self.sticks[(row, col)] = Stick(row, col, game)
131
+ self.display("... a moment please ...")
132
+ self.screen.tracer(True)
133
+
134
+ def display(self, msg1, msg2=None):
135
+ self.screen.tracer(False)
136
+ self.writer.clear()
137
+ if msg2 is not None:
138
+ self.writer.goto(0, - SCREENHEIGHT // 2 + 48)
139
+ self.writer.pencolor("red")
140
+ self.writer.write(msg2, align="center", font=("Courier",18,"bold"))
141
+ self.writer.goto(0, - SCREENHEIGHT // 2 + 20)
142
+ self.writer.pencolor("black")
143
+ self.writer.write(msg1, align="center", font=("Courier",14,"bold"))
144
+ self.screen.tracer(True)
145
+
146
+ def setup(self):
147
+ self.screen.tracer(False)
148
+ for row in range(3):
149
+ for col in range(self.model.sticks[row]):
150
+ self.sticks[(row, col)].color(SCOLOR)
151
+ for row in range(3):
152
+ for col in range(self.model.sticks[row], MAXSTICKS):
153
+ self.sticks[(row, col)].color("white")
154
+ self.display("Your turn! Click leftmost stick to remove.")
155
+ self.screen.tracer(True)
156
+
157
+ def notify_move(self, row, col, maxspalte, player):
158
+ if player == 0:
159
+ farbe = HCOLOR
160
+ for s in range(col, maxspalte):
161
+ self.sticks[(row, s)].color(farbe)
162
+ else:
163
+ self.display(" ... thinking ... ")
164
+ time.sleep(0.5)
165
+ self.display(" ... thinking ... aaah ...")
166
+ farbe = COLOR
167
+ for s in range(maxspalte-1, col-1, -1):
168
+ time.sleep(0.2)
169
+ self.sticks[(row, s)].color(farbe)
170
+ self.display("Your turn! Click leftmost stick to remove.")
171
+
172
+ def notify_over(self):
173
+ if self.game.model.winner == 0:
174
+ msg2 = "Congrats. You're the winner!!!"
175
+ else:
176
+ msg2 = "Sorry, the computer is the winner."
177
+ self.display("To play again press space bar. To leave press ESC.", msg2)
178
+
179
+ def clear(self):
180
+ if self.game.state == Nim.OVER:
181
+ self.screen.clear()
182
+
183
+
184
+ class NimController(object):
185
+
186
+ def __init__(self, game):
187
+ self.game = game
188
+ self.sticks = game.view.sticks
189
+ self.BUSY = False
190
+ for stick in self.sticks.values():
191
+ stick.onclick(stick.makemove)
192
+ self.game.screen.onkey(self.game.model.setup, "space")
193
+ self.game.screen.onkey(self.game.view.clear, "Escape")
194
+ self.game.view.display("Press space bar to start game")
195
+ self.game.screen.listen()
196
+
197
+ def notify_move(self, row, col):
198
+ if self.BUSY:
199
+ return
200
+ self.BUSY = True
201
+ self.game.model.notify_move(row, col)
202
+ self.BUSY = False
203
+
204
+
205
+ class Nim(object):
206
+ CREATED = 0
207
+ RUNNING = 1
208
+ OVER = 2
209
+ def __init__(self, screen):
210
+ self.state = Nim.CREATED
211
+ self.screen = screen
212
+ self.model = NimModel(self)
213
+ self.view = NimView(self)
214
+ self.controller = NimController(self)
215
+
216
+
217
+ def main():
218
+ mainscreen = turtle.Screen()
219
+ mainscreen.mode("standard")
220
+ mainscreen.setup(SCREENWIDTH, SCREENHEIGHT)
221
+ nim = Nim(mainscreen)
222
+ return "EVENTLOOP"
223
+
224
+ if __name__ == "__main__":
225
+ main()
226
+ turtle.mainloop()
parrot/lib/python3.10/turtledemo/paint.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_paint.py
5
+
6
+ A simple event-driven paint program
7
+
8
+ - left mouse button moves turtle
9
+ - middle mouse button changes color
10
+ - right mouse button toggles between pen up
11
+ (no line drawn when the turtle moves) and
12
+ pen down (line is drawn). If pen up follows
13
+ at least two pen-down moves, the polygon that
14
+ includes the starting point is filled.
15
+ -------------------------------------------
16
+ Play around by clicking into the canvas
17
+ using all three mouse buttons.
18
+ -------------------------------------------
19
+ To exit press STOP button
20
+ -------------------------------------------
21
+ """
22
+ from turtle import *
23
+
24
+ def switchupdown(x=0, y=0):
25
+ if pen()["pendown"]:
26
+ end_fill()
27
+ up()
28
+ else:
29
+ down()
30
+ begin_fill()
31
+
32
+ def changecolor(x=0, y=0):
33
+ global colors
34
+ colors = colors[1:]+colors[:1]
35
+ color(colors[0])
36
+
37
+ def main():
38
+ global colors
39
+ shape("circle")
40
+ resizemode("user")
41
+ shapesize(.5)
42
+ width(3)
43
+ colors=["red", "green", "blue", "yellow"]
44
+ color(colors[0])
45
+ switchupdown()
46
+ onscreenclick(goto,1)
47
+ onscreenclick(changecolor,2)
48
+ onscreenclick(switchupdown,3)
49
+ return "EVENTLOOP"
50
+
51
+ if __name__ == "__main__":
52
+ msg = main()
53
+ print(msg)
54
+ mainloop()
parrot/lib/python3.10/turtledemo/peace.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_peace.py
5
+
6
+ A simple drawing suitable as a beginner's
7
+ programming example. Aside from the
8
+ peacecolors assignment and the for loop,
9
+ it only uses turtle commands.
10
+ """
11
+
12
+ from turtle import *
13
+
14
+ def main():
15
+ peacecolors = ("red3", "orange", "yellow",
16
+ "seagreen4", "orchid4",
17
+ "royalblue1", "dodgerblue4")
18
+
19
+ reset()
20
+ Screen()
21
+ up()
22
+ goto(-320,-195)
23
+ width(70)
24
+
25
+ for pcolor in peacecolors:
26
+ color(pcolor)
27
+ down()
28
+ forward(640)
29
+ up()
30
+ backward(640)
31
+ left(90)
32
+ forward(66)
33
+ right(90)
34
+
35
+ width(25)
36
+ color("white")
37
+ goto(0,-170)
38
+ down()
39
+
40
+ circle(170)
41
+ left(90)
42
+ forward(340)
43
+ up()
44
+ left(180)
45
+ forward(170)
46
+ right(45)
47
+ down()
48
+ forward(170)
49
+ up()
50
+ backward(170)
51
+ left(90)
52
+ down()
53
+ forward(170)
54
+ up()
55
+
56
+ goto(0,300) # vanish if hideturtle() is not available ;-)
57
+ return "Done!"
58
+
59
+ if __name__ == "__main__":
60
+ main()
61
+ mainloop()
parrot/lib/python3.10/turtledemo/penrose.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ xturtle-example-suite:
3
+
4
+ xtx_kites_and_darts.py
5
+
6
+ Constructs two aperiodic penrose-tilings,
7
+ consisting of kites and darts, by the method
8
+ of inflation in six steps.
9
+
10
+ Starting points are the patterns "sun"
11
+ consisting of five kites and "star"
12
+ consisting of five darts.
13
+
14
+ For more information see:
15
+ http://en.wikipedia.org/wiki/Penrose_tiling
16
+ -------------------------------------------
17
+ """
18
+ from turtle import *
19
+ from math import cos, pi
20
+ from time import perf_counter as clock, sleep
21
+
22
+ f = (5**0.5-1)/2.0 # (sqrt(5)-1)/2 -- golden ratio
23
+ d = 2 * cos(3*pi/10)
24
+
25
+ def kite(l):
26
+ fl = f * l
27
+ lt(36)
28
+ fd(l)
29
+ rt(108)
30
+ fd(fl)
31
+ rt(36)
32
+ fd(fl)
33
+ rt(108)
34
+ fd(l)
35
+ rt(144)
36
+
37
+ def dart(l):
38
+ fl = f * l
39
+ lt(36)
40
+ fd(l)
41
+ rt(144)
42
+ fd(fl)
43
+ lt(36)
44
+ fd(fl)
45
+ rt(144)
46
+ fd(l)
47
+ rt(144)
48
+
49
+ def inflatekite(l, n):
50
+ if n == 0:
51
+ px, py = pos()
52
+ h, x, y = int(heading()), round(px,3), round(py,3)
53
+ tiledict[(h,x,y)] = True
54
+ return
55
+ fl = f * l
56
+ lt(36)
57
+ inflatedart(fl, n-1)
58
+ fd(l)
59
+ rt(144)
60
+ inflatekite(fl, n-1)
61
+ lt(18)
62
+ fd(l*d)
63
+ rt(162)
64
+ inflatekite(fl, n-1)
65
+ lt(36)
66
+ fd(l)
67
+ rt(180)
68
+ inflatedart(fl, n-1)
69
+ lt(36)
70
+
71
+ def inflatedart(l, n):
72
+ if n == 0:
73
+ px, py = pos()
74
+ h, x, y = int(heading()), round(px,3), round(py,3)
75
+ tiledict[(h,x,y)] = False
76
+ return
77
+ fl = f * l
78
+ inflatekite(fl, n-1)
79
+ lt(36)
80
+ fd(l)
81
+ rt(180)
82
+ inflatedart(fl, n-1)
83
+ lt(54)
84
+ fd(l*d)
85
+ rt(126)
86
+ inflatedart(fl, n-1)
87
+ fd(l)
88
+ rt(144)
89
+
90
+ def draw(l, n, th=2):
91
+ clear()
92
+ l = l * f**n
93
+ shapesize(l/100.0, l/100.0, th)
94
+ for k in tiledict:
95
+ h, x, y = k
96
+ setpos(x, y)
97
+ setheading(h)
98
+ if tiledict[k]:
99
+ shape("kite")
100
+ color("black", (0, 0.75, 0))
101
+ else:
102
+ shape("dart")
103
+ color("black", (0.75, 0, 0))
104
+ stamp()
105
+
106
+ def sun(l, n):
107
+ for i in range(5):
108
+ inflatekite(l, n)
109
+ lt(72)
110
+
111
+ def star(l,n):
112
+ for i in range(5):
113
+ inflatedart(l, n)
114
+ lt(72)
115
+
116
+ def makeshapes():
117
+ tracer(0)
118
+ begin_poly()
119
+ kite(100)
120
+ end_poly()
121
+ register_shape("kite", get_poly())
122
+ begin_poly()
123
+ dart(100)
124
+ end_poly()
125
+ register_shape("dart", get_poly())
126
+ tracer(1)
127
+
128
+ def start():
129
+ reset()
130
+ ht()
131
+ pu()
132
+ makeshapes()
133
+ resizemode("user")
134
+
135
+ def test(l=200, n=4, fun=sun, startpos=(0,0), th=2):
136
+ global tiledict
137
+ goto(startpos)
138
+ setheading(0)
139
+ tiledict = {}
140
+ tracer(0)
141
+ fun(l, n)
142
+ draw(l, n, th)
143
+ tracer(1)
144
+ nk = len([x for x in tiledict if tiledict[x]])
145
+ nd = len([x for x in tiledict if not tiledict[x]])
146
+ print("%d kites and %d darts = %d pieces." % (nk, nd, nk+nd))
147
+
148
+ def demo(fun=sun):
149
+ start()
150
+ for i in range(8):
151
+ a = clock()
152
+ test(300, i, fun)
153
+ b = clock()
154
+ t = b - a
155
+ if t < 2:
156
+ sleep(2 - t)
157
+
158
+ def main():
159
+ #title("Penrose-tiling with kites and darts.")
160
+ mode("logo")
161
+ bgcolor(0.3, 0.3, 0)
162
+ demo(sun)
163
+ sleep(2)
164
+ demo(star)
165
+ pencolor("black")
166
+ goto(0,-200)
167
+ pencolor(0.7,0.7,1)
168
+ write("Please wait...",
169
+ align="center", font=('Arial Black', 36, 'bold'))
170
+ test(600, 8, startpos=(70, 117))
171
+ return "Done"
172
+
173
+ if __name__ == "__main__":
174
+ msg = main()
175
+ mainloop()
parrot/lib/python3.10/turtledemo/planet_and_moon.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_planets_and_moon.py
5
+
6
+ Gravitational system simulation using the
7
+ approximation method from Feynman-lectures,
8
+ p.9-8, using turtlegraphics.
9
+
10
+ Example: heavy central body, light planet,
11
+ very light moon!
12
+ Planet has a circular orbit, moon a stable
13
+ orbit around the planet.
14
+
15
+ You can hold the movement temporarily by
16
+ pressing the left mouse button with the
17
+ mouse over the scrollbar of the canvas.
18
+
19
+ """
20
+ from turtle import Shape, Turtle, mainloop, Vec2D as Vec
21
+
22
+ G = 8
23
+
24
+ class GravSys(object):
25
+ def __init__(self):
26
+ self.planets = []
27
+ self.t = 0
28
+ self.dt = 0.01
29
+ def init(self):
30
+ for p in self.planets:
31
+ p.init()
32
+ def start(self):
33
+ for i in range(10000):
34
+ self.t += self.dt
35
+ for p in self.planets:
36
+ p.step()
37
+
38
+ class Star(Turtle):
39
+ def __init__(self, m, x, v, gravSys, shape):
40
+ Turtle.__init__(self, shape=shape)
41
+ self.penup()
42
+ self.m = m
43
+ self.setpos(x)
44
+ self.v = v
45
+ gravSys.planets.append(self)
46
+ self.gravSys = gravSys
47
+ self.resizemode("user")
48
+ self.pendown()
49
+ def init(self):
50
+ dt = self.gravSys.dt
51
+ self.a = self.acc()
52
+ self.v = self.v + 0.5*dt*self.a
53
+ def acc(self):
54
+ a = Vec(0,0)
55
+ for planet in self.gravSys.planets:
56
+ if planet != self:
57
+ v = planet.pos()-self.pos()
58
+ a += (G*planet.m/abs(v)**3)*v
59
+ return a
60
+ def step(self):
61
+ dt = self.gravSys.dt
62
+ self.setpos(self.pos() + dt*self.v)
63
+ if self.gravSys.planets.index(self) != 0:
64
+ self.setheading(self.towards(self.gravSys.planets[0]))
65
+ self.a = self.acc()
66
+ self.v = self.v + dt*self.a
67
+
68
+ ## create compound yellow/blue turtleshape for planets
69
+
70
+ def main():
71
+ s = Turtle()
72
+ s.reset()
73
+ s.getscreen().tracer(0,0)
74
+ s.ht()
75
+ s.pu()
76
+ s.fd(6)
77
+ s.lt(90)
78
+ s.begin_poly()
79
+ s.circle(6, 180)
80
+ s.end_poly()
81
+ m1 = s.get_poly()
82
+ s.begin_poly()
83
+ s.circle(6,180)
84
+ s.end_poly()
85
+ m2 = s.get_poly()
86
+
87
+ planetshape = Shape("compound")
88
+ planetshape.addcomponent(m1,"orange")
89
+ planetshape.addcomponent(m2,"blue")
90
+ s.getscreen().register_shape("planet", planetshape)
91
+ s.getscreen().tracer(1,0)
92
+
93
+ ## setup gravitational system
94
+ gs = GravSys()
95
+ sun = Star(1000000, Vec(0,0), Vec(0,-2.5), gs, "circle")
96
+ sun.color("yellow")
97
+ sun.shapesize(1.8)
98
+ sun.pu()
99
+ earth = Star(12500, Vec(210,0), Vec(0,195), gs, "planet")
100
+ earth.pencolor("green")
101
+ earth.shapesize(0.8)
102
+ moon = Star(1, Vec(220,0), Vec(0,295), gs, "planet")
103
+ moon.pencolor("blue")
104
+ moon.shapesize(0.5)
105
+ gs.init()
106
+ gs.start()
107
+ return "Done!"
108
+
109
+ if __name__ == '__main__':
110
+ main()
111
+ mainloop()
parrot/lib/python3.10/turtledemo/rosette.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_wikipedia3.py
4
+
5
+ This example is
6
+ inspired by the Wikipedia article on turtle
7
+ graphics. (See example wikipedia1 for URLs)
8
+
9
+ First we create (ne-1) (i.e. 35 in this
10
+ example) copies of our first turtle p.
11
+ Then we let them perform their steps in
12
+ parallel.
13
+
14
+ Followed by a complete undo().
15
+ """
16
+ from turtle import Screen, Turtle, mainloop
17
+ from time import perf_counter as clock, sleep
18
+
19
+ def mn_eck(p, ne,sz):
20
+ turtlelist = [p]
21
+ #create ne-1 additional turtles
22
+ for i in range(1,ne):
23
+ q = p.clone()
24
+ q.rt(360.0/ne)
25
+ turtlelist.append(q)
26
+ p = q
27
+ for i in range(ne):
28
+ c = abs(ne/2.0-i)/(ne*.7)
29
+ # let those ne turtles make a step
30
+ # in parallel:
31
+ for t in turtlelist:
32
+ t.rt(360./ne)
33
+ t.pencolor(1-c,0,c)
34
+ t.fd(sz)
35
+
36
+ def main():
37
+ s = Screen()
38
+ s.bgcolor("black")
39
+ p=Turtle()
40
+ p.speed(0)
41
+ p.hideturtle()
42
+ p.pencolor("red")
43
+ p.pensize(3)
44
+
45
+ s.tracer(36,0)
46
+
47
+ at = clock()
48
+ mn_eck(p, 36, 19)
49
+ et = clock()
50
+ z1 = et-at
51
+
52
+ sleep(1)
53
+
54
+ at = clock()
55
+ while any(t.undobufferentries() for t in s.turtles()):
56
+ for t in s.turtles():
57
+ t.undo()
58
+ et = clock()
59
+ return "runtime: %.3f sec" % (z1+et-at)
60
+
61
+
62
+ if __name__ == '__main__':
63
+ msg = main()
64
+ print(msg)
65
+ mainloop()
parrot/lib/python3.10/turtledemo/round_dance.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ turtle-example-suite:
2
+
3
+ tdemo_round_dance.py
4
+
5
+ (Needs version 1.1 of the turtle module that
6
+ comes with Python 3.1)
7
+
8
+ Dancing turtles have a compound shape
9
+ consisting of a series of triangles of
10
+ decreasing size.
11
+
12
+ Turtles march along a circle while rotating
13
+ pairwise in opposite direction, with one
14
+ exception. Does that breaking of symmetry
15
+ enhance the attractiveness of the example?
16
+
17
+ Press any key to stop the animation.
18
+
19
+ Technically: demonstrates use of compound
20
+ shapes, transformation of shapes as well as
21
+ cloning turtles. The animation is
22
+ controlled through update().
23
+ """
24
+
25
+ from turtle import *
26
+
27
+ def stop():
28
+ global running
29
+ running = False
30
+
31
+ def main():
32
+ global running
33
+ clearscreen()
34
+ bgcolor("gray10")
35
+ tracer(False)
36
+ shape("triangle")
37
+ f = 0.793402
38
+ phi = 9.064678
39
+ s = 5
40
+ c = 1
41
+ # create compound shape
42
+ sh = Shape("compound")
43
+ for i in range(10):
44
+ shapesize(s)
45
+ p =get_shapepoly()
46
+ s *= f
47
+ c *= f
48
+ tilt(-phi)
49
+ sh.addcomponent(p, (c, 0.25, 1-c), "black")
50
+ register_shape("multitri", sh)
51
+ # create dancers
52
+ shapesize(1)
53
+ shape("multitri")
54
+ pu()
55
+ setpos(0, -200)
56
+ dancers = []
57
+ for i in range(180):
58
+ fd(7)
59
+ tilt(-4)
60
+ lt(2)
61
+ update()
62
+ if i % 12 == 0:
63
+ dancers.append(clone())
64
+ home()
65
+ # dance
66
+ running = True
67
+ onkeypress(stop)
68
+ listen()
69
+ cs = 1
70
+ while running:
71
+ ta = -4
72
+ for dancer in dancers:
73
+ dancer.fd(7)
74
+ dancer.lt(2)
75
+ dancer.tilt(ta)
76
+ ta = -4 if ta > 0 else 2
77
+ if cs < 180:
78
+ right(4)
79
+ shapesize(cs)
80
+ cs *= 1.005
81
+ update()
82
+ return "DONE!"
83
+
84
+ if __name__=='__main__':
85
+ print(main())
86
+ mainloop()
parrot/lib/python3.10/turtledemo/sorting_animate.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+
4
+ sorting_animation.py
5
+
6
+ A minimal sorting algorithm animation:
7
+ Sorts a shelf of 10 blocks using insertion
8
+ sort, selection sort and quicksort.
9
+
10
+ Shelfs are implemented using builtin lists.
11
+
12
+ Blocks are turtles with shape "square", but
13
+ stretched to rectangles by shapesize()
14
+ ---------------------------------------
15
+ To exit press space button
16
+ ---------------------------------------
17
+ """
18
+ from turtle import *
19
+ import random
20
+
21
+
22
+ class Block(Turtle):
23
+
24
+ def __init__(self, size):
25
+ self.size = size
26
+ Turtle.__init__(self, shape="square", visible=False)
27
+ self.pu()
28
+ self.shapesize(size * 1.5, 1.5, 2) # square-->rectangle
29
+ self.fillcolor("black")
30
+ self.st()
31
+
32
+ def glow(self):
33
+ self.fillcolor("red")
34
+
35
+ def unglow(self):
36
+ self.fillcolor("black")
37
+
38
+ def __repr__(self):
39
+ return "Block size: {0}".format(self.size)
40
+
41
+
42
+ class Shelf(list):
43
+
44
+ def __init__(self, y):
45
+ "create a shelf. y is y-position of first block"
46
+ self.y = y
47
+ self.x = -150
48
+
49
+ def push(self, d):
50
+ width, _, _ = d.shapesize()
51
+ # align blocks by the bottom edge
52
+ y_offset = width / 2 * 20
53
+ d.sety(self.y + y_offset)
54
+ d.setx(self.x + 34 * len(self))
55
+ self.append(d)
56
+
57
+ def _close_gap_from_i(self, i):
58
+ for b in self[i:]:
59
+ xpos, _ = b.pos()
60
+ b.setx(xpos - 34)
61
+
62
+ def _open_gap_from_i(self, i):
63
+ for b in self[i:]:
64
+ xpos, _ = b.pos()
65
+ b.setx(xpos + 34)
66
+
67
+ def pop(self, key):
68
+ b = list.pop(self, key)
69
+ b.glow()
70
+ b.sety(200)
71
+ self._close_gap_from_i(key)
72
+ return b
73
+
74
+ def insert(self, key, b):
75
+ self._open_gap_from_i(key)
76
+ list.insert(self, key, b)
77
+ b.setx(self.x + 34 * key)
78
+ width, _, _ = b.shapesize()
79
+ # align blocks by the bottom edge
80
+ y_offset = width / 2 * 20
81
+ b.sety(self.y + y_offset)
82
+ b.unglow()
83
+
84
+ def isort(shelf):
85
+ length = len(shelf)
86
+ for i in range(1, length):
87
+ hole = i
88
+ while hole > 0 and shelf[i].size < shelf[hole - 1].size:
89
+ hole = hole - 1
90
+ shelf.insert(hole, shelf.pop(i))
91
+ return
92
+
93
+ def ssort(shelf):
94
+ length = len(shelf)
95
+ for j in range(0, length - 1):
96
+ imin = j
97
+ for i in range(j + 1, length):
98
+ if shelf[i].size < shelf[imin].size:
99
+ imin = i
100
+ if imin != j:
101
+ shelf.insert(j, shelf.pop(imin))
102
+
103
+ def partition(shelf, left, right, pivot_index):
104
+ pivot = shelf[pivot_index]
105
+ shelf.insert(right, shelf.pop(pivot_index))
106
+ store_index = left
107
+ for i in range(left, right): # range is non-inclusive of ending value
108
+ if shelf[i].size < pivot.size:
109
+ shelf.insert(store_index, shelf.pop(i))
110
+ store_index = store_index + 1
111
+ shelf.insert(store_index, shelf.pop(right)) # move pivot to correct position
112
+ return store_index
113
+
114
+ def qsort(shelf, left, right):
115
+ if left < right:
116
+ pivot_index = left
117
+ pivot_new_index = partition(shelf, left, right, pivot_index)
118
+ qsort(shelf, left, pivot_new_index - 1)
119
+ qsort(shelf, pivot_new_index + 1, right)
120
+
121
+ def randomize():
122
+ disable_keys()
123
+ clear()
124
+ target = list(range(10))
125
+ random.shuffle(target)
126
+ for i, t in enumerate(target):
127
+ for j in range(i, len(s)):
128
+ if s[j].size == t + 1:
129
+ s.insert(i, s.pop(j))
130
+ show_text(instructions1)
131
+ show_text(instructions2, line=1)
132
+ enable_keys()
133
+
134
+ def show_text(text, line=0):
135
+ line = 20 * line
136
+ goto(0,-250 - line)
137
+ write(text, align="center", font=("Courier", 16, "bold"))
138
+
139
+ def start_ssort():
140
+ disable_keys()
141
+ clear()
142
+ show_text("Selection Sort")
143
+ ssort(s)
144
+ clear()
145
+ show_text(instructions1)
146
+ show_text(instructions2, line=1)
147
+ enable_keys()
148
+
149
+ def start_isort():
150
+ disable_keys()
151
+ clear()
152
+ show_text("Insertion Sort")
153
+ isort(s)
154
+ clear()
155
+ show_text(instructions1)
156
+ show_text(instructions2, line=1)
157
+ enable_keys()
158
+
159
+ def start_qsort():
160
+ disable_keys()
161
+ clear()
162
+ show_text("Quicksort")
163
+ qsort(s, 0, len(s) - 1)
164
+ clear()
165
+ show_text(instructions1)
166
+ show_text(instructions2, line=1)
167
+ enable_keys()
168
+
169
+ def init_shelf():
170
+ global s
171
+ s = Shelf(-200)
172
+ vals = (4, 2, 8, 9, 1, 5, 10, 3, 7, 6)
173
+ for i in vals:
174
+ s.push(Block(i))
175
+
176
+ def disable_keys():
177
+ onkey(None, "s")
178
+ onkey(None, "i")
179
+ onkey(None, "q")
180
+ onkey(None, "r")
181
+
182
+ def enable_keys():
183
+ onkey(start_isort, "i")
184
+ onkey(start_ssort, "s")
185
+ onkey(start_qsort, "q")
186
+ onkey(randomize, "r")
187
+ onkey(bye, "space")
188
+
189
+ def main():
190
+ getscreen().clearscreen()
191
+ ht(); penup()
192
+ init_shelf()
193
+ show_text(instructions1)
194
+ show_text(instructions2, line=1)
195
+ enable_keys()
196
+ listen()
197
+ return "EVENTLOOP"
198
+
199
+ instructions1 = "press i for insertion sort, s for selection sort, q for quicksort"
200
+ instructions2 = "spacebar to quit, r to randomize"
201
+
202
+ if __name__=="__main__":
203
+ msg = main()
204
+ mainloop()
parrot/lib/python3.10/turtledemo/tree.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_tree.py
5
+
6
+ Displays a 'breadth-first-tree' - in contrast
7
+ to the classical Logo tree drawing programs,
8
+ which use a depth-first-algorithm.
9
+
10
+ Uses:
11
+ (1) a tree-generator, where the drawing is
12
+ quasi the side-effect, whereas the generator
13
+ always yields None.
14
+ (2) Turtle-cloning: At each branching point
15
+ the current pen is cloned. So in the end
16
+ there are 1024 turtles.
17
+ """
18
+ from turtle import Turtle, mainloop
19
+ from time import perf_counter as clock
20
+
21
+ def tree(plist, l, a, f):
22
+ """ plist is list of pens
23
+ l is length of branch
24
+ a is half of the angle between 2 branches
25
+ f is factor by which branch is shortened
26
+ from level to level."""
27
+ if l > 3:
28
+ lst = []
29
+ for p in plist:
30
+ p.forward(l)
31
+ q = p.clone()
32
+ p.left(a)
33
+ q.right(a)
34
+ lst.append(p)
35
+ lst.append(q)
36
+ for x in tree(lst, l*f, a, f):
37
+ yield None
38
+
39
+ def maketree():
40
+ p = Turtle()
41
+ p.setundobuffer(None)
42
+ p.hideturtle()
43
+ p.speed(0)
44
+ p.getscreen().tracer(30,0)
45
+ p.left(90)
46
+ p.penup()
47
+ p.forward(-210)
48
+ p.pendown()
49
+ t = tree([p], 200, 65, 0.6375)
50
+ for x in t:
51
+ pass
52
+
53
+ def main():
54
+ a=clock()
55
+ maketree()
56
+ b=clock()
57
+ return "done: %.2f sec." % (b-a)
58
+
59
+ if __name__ == "__main__":
60
+ msg = main()
61
+ print(msg)
62
+ mainloop()
parrot/lib/python3.10/turtledemo/turtle.cfg ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ width = 800
2
+ height = 600
3
+ canvwidth = 1200
4
+ canvheight = 900
5
+ shape = arrow
6
+ mode = standard
7
+ resizemode = auto
8
+ fillcolor = ""
9
+ title = Python turtle graphics demo.
10
+
parrot/lib/python3.10/turtledemo/two_canvases.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """turtledemo.two_canvases
2
+
3
+ Use TurtleScreen and RawTurtle to draw on two
4
+ distinct canvases in a separate window. The
5
+ new window must be separately closed in
6
+ addition to pressing the STOP button.
7
+ """
8
+
9
+ from turtle import TurtleScreen, RawTurtle, TK
10
+
11
+ def main():
12
+ root = TK.Tk()
13
+ cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff")
14
+ cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee")
15
+ cv1.pack()
16
+ cv2.pack()
17
+
18
+ s1 = TurtleScreen(cv1)
19
+ s1.bgcolor(0.85, 0.85, 1)
20
+ s2 = TurtleScreen(cv2)
21
+ s2.bgcolor(1, 0.85, 0.85)
22
+
23
+ p = RawTurtle(s1)
24
+ q = RawTurtle(s2)
25
+
26
+ p.color("red", (1, 0.85, 0.85))
27
+ p.width(3)
28
+ q.color("blue", (0.85, 0.85, 1))
29
+ q.width(3)
30
+
31
+ for t in p,q:
32
+ t.shape("turtle")
33
+ t.lt(36)
34
+
35
+ q.lt(180)
36
+
37
+ for t in p, q:
38
+ t.begin_fill()
39
+ for i in range(5):
40
+ for t in p, q:
41
+ t.fd(50)
42
+ t.lt(72)
43
+ for t in p,q:
44
+ t.end_fill()
45
+ t.lt(54)
46
+ t.pu()
47
+ t.bk(50)
48
+
49
+ return "EVENTLOOP"
50
+
51
+
52
+ if __name__ == '__main__':
53
+ main()
54
+ TK.mainloop() # keep window open until user closes it
parrot/lib/python3.10/turtledemo/yinyang.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """ turtle-example-suite:
3
+
4
+ tdemo_yinyang.py
5
+
6
+ Another drawing suitable as a beginner's
7
+ programming example.
8
+
9
+ The small circles are drawn by the circle
10
+ command.
11
+
12
+ """
13
+
14
+ from turtle import *
15
+
16
+ def yin(radius, color1, color2):
17
+ width(3)
18
+ color("black", color1)
19
+ begin_fill()
20
+ circle(radius/2., 180)
21
+ circle(radius, 180)
22
+ left(180)
23
+ circle(-radius/2., 180)
24
+ end_fill()
25
+ left(90)
26
+ up()
27
+ forward(radius*0.35)
28
+ right(90)
29
+ down()
30
+ color(color1, color2)
31
+ begin_fill()
32
+ circle(radius*0.15)
33
+ end_fill()
34
+ left(90)
35
+ up()
36
+ backward(radius*0.35)
37
+ down()
38
+ left(90)
39
+
40
+ def main():
41
+ reset()
42
+ yin(200, "black", "white")
43
+ yin(200, "white", "black")
44
+ ht()
45
+ return "Done!"
46
+
47
+ if __name__ == '__main__':
48
+ main()
49
+ mainloop()
parrot/lib/python3.10/xml/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (947 Bytes). View file