Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +4 -0
- material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908306_m.tif +3 -0
- material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif +3 -0
- material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif +3 -0
- material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif +3 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/__pycache__/deepreload.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/clipboard.py +102 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/demo.py +672 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/display.py +677 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/pretty.py +961 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/__init__.py +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/console.py +19 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/debugger.py +187 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/embed.py +426 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/interactiveshell.py +1146 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ipapp.py +338 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/magics.py +214 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/prompts.py +128 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ptutils.py +204 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/__init__.py +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/fake_llm.py +89 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_debug_magic.py +82 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_embed.py +138 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_help.py +30 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_interactivshell.py +255 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_pt_inputhooks.py +50 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_shortcuts.py +509 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/__init__.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/decorators.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/globalipapp.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/ipunittest.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/skipdoctest.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/tools.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/README.txt +34 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__init__.py +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/__init__.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/dtexample.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/ipdoctest.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/pytest_ipdoctest.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/setup.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simple.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simplevars.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_ipdoctest.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_refs.cpython-310.pyc +0 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/dtexample.py +167 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/ipdoctest.py +299 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/pytest_ipdoctest.py +879 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/setup.py +18 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simple.py +44 -0
- material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simplevars.py +2 -0
.gitattributes
CHANGED
|
@@ -411,3 +411,7 @@ material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:
|
|
| 411 |
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908284_m.tif filter=lfs diff=lfs merge=lfs -text
|
| 412 |
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908324_m.tif filter=lfs diff=lfs merge=lfs -text
|
| 413 |
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908288/1908288.tif filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908284_m.tif filter=lfs diff=lfs merge=lfs -text
|
| 412 |
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908324_m.tif filter=lfs diff=lfs merge=lfs -text
|
| 413 |
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908288/1908288.tif filter=lfs diff=lfs merge=lfs -text
|
| 414 |
+
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif filter=lfs diff=lfs merge=lfs -text
|
| 415 |
+
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif filter=lfs diff=lfs merge=lfs -text
|
| 416 |
+
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908306_m.tif filter=lfs diff=lfs merge=lfs -text
|
| 417 |
+
material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif filter=lfs diff=lfs merge=lfs -text
|
material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908306_m.tif
ADDED
|
|
Git LFS Details
|
material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908266/1908266.tif
ADDED
|
|
Git LFS Details
|
material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908300/1908300.tif
ADDED
|
|
Git LFS Details
|
material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Output/1908274/1908274.tif
ADDED
|
|
Git LFS Details
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/__pycache__/deepreload.cpython-310.pyc
ADDED
|
Binary file (6.37 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/clipboard.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Utilities for accessing the platform's clipboard.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import subprocess
|
| 6 |
+
|
| 7 |
+
from IPython.core.error import TryNext
|
| 8 |
+
import IPython.utils.py3compat as py3compat
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ClipboardEmpty(ValueError):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def win32_clipboard_get():
|
| 16 |
+
""" Get the current clipboard's text on Windows.
|
| 17 |
+
|
| 18 |
+
Requires Mark Hammond's pywin32 extensions.
|
| 19 |
+
"""
|
| 20 |
+
try:
|
| 21 |
+
import win32clipboard
|
| 22 |
+
except ImportError as e:
|
| 23 |
+
raise TryNext("Getting text from the clipboard requires the pywin32 "
|
| 24 |
+
"extensions: http://sourceforge.net/projects/pywin32/") from e
|
| 25 |
+
win32clipboard.OpenClipboard()
|
| 26 |
+
try:
|
| 27 |
+
text = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
|
| 28 |
+
except (TypeError, win32clipboard.error):
|
| 29 |
+
try:
|
| 30 |
+
text = win32clipboard.GetClipboardData(win32clipboard.CF_TEXT)
|
| 31 |
+
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
|
| 32 |
+
except (TypeError, win32clipboard.error) as e:
|
| 33 |
+
raise ClipboardEmpty from e
|
| 34 |
+
finally:
|
| 35 |
+
win32clipboard.CloseClipboard()
|
| 36 |
+
return text
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def osx_clipboard_get() -> str:
|
| 40 |
+
""" Get the clipboard's text on OS X.
|
| 41 |
+
"""
|
| 42 |
+
p = subprocess.Popen(['pbpaste', '-Prefer', 'ascii'],
|
| 43 |
+
stdout=subprocess.PIPE)
|
| 44 |
+
bytes_, stderr = p.communicate()
|
| 45 |
+
# Text comes in with old Mac \r line endings. Change them to \n.
|
| 46 |
+
bytes_ = bytes_.replace(b'\r', b'\n')
|
| 47 |
+
text = py3compat.decode(bytes_)
|
| 48 |
+
return text
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def tkinter_clipboard_get():
|
| 52 |
+
""" Get the clipboard's text using Tkinter.
|
| 53 |
+
|
| 54 |
+
This is the default on systems that are not Windows or OS X. It may
|
| 55 |
+
interfere with other UI toolkits and should be replaced with an
|
| 56 |
+
implementation that uses that toolkit.
|
| 57 |
+
"""
|
| 58 |
+
try:
|
| 59 |
+
from tkinter import Tk, TclError
|
| 60 |
+
except ImportError as e:
|
| 61 |
+
raise TryNext("Getting text from the clipboard on this platform requires tkinter.") from e
|
| 62 |
+
|
| 63 |
+
root = Tk()
|
| 64 |
+
root.withdraw()
|
| 65 |
+
try:
|
| 66 |
+
text = root.clipboard_get()
|
| 67 |
+
except TclError as e:
|
| 68 |
+
raise ClipboardEmpty from e
|
| 69 |
+
finally:
|
| 70 |
+
root.destroy()
|
| 71 |
+
text = py3compat.cast_unicode(text, py3compat.DEFAULT_ENCODING)
|
| 72 |
+
return text
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def wayland_clipboard_get():
|
| 76 |
+
"""Get the clipboard's text under Wayland using wl-paste command.
|
| 77 |
+
|
| 78 |
+
This requires Wayland and wl-clipboard installed and running.
|
| 79 |
+
"""
|
| 80 |
+
if os.environ.get("XDG_SESSION_TYPE") != "wayland":
|
| 81 |
+
raise TryNext("wayland is not detected")
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
with subprocess.Popen(["wl-paste"], stdout=subprocess.PIPE) as p:
|
| 85 |
+
raw, err = p.communicate()
|
| 86 |
+
if p.wait():
|
| 87 |
+
raise TryNext(err)
|
| 88 |
+
except FileNotFoundError as e:
|
| 89 |
+
raise TryNext(
|
| 90 |
+
"Getting text from the clipboard under Wayland requires the wl-clipboard "
|
| 91 |
+
"extension: https://github.com/bugaevc/wl-clipboard"
|
| 92 |
+
) from e
|
| 93 |
+
|
| 94 |
+
if not raw:
|
| 95 |
+
raise ClipboardEmpty
|
| 96 |
+
|
| 97 |
+
try:
|
| 98 |
+
text = py3compat.decode(raw)
|
| 99 |
+
except UnicodeDecodeError as e:
|
| 100 |
+
raise ClipboardEmpty from e
|
| 101 |
+
|
| 102 |
+
return text
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/demo.py
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module for interactive demos using IPython.
|
| 2 |
+
|
| 3 |
+
This module implements a few classes for running Python scripts interactively
|
| 4 |
+
in IPython for demonstrations. With very simple markup (a few tags in
|
| 5 |
+
comments), you can control points where the script stops executing and returns
|
| 6 |
+
control to IPython.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
Provided classes
|
| 10 |
+
----------------
|
| 11 |
+
|
| 12 |
+
The classes are (see their docstrings for further details):
|
| 13 |
+
|
| 14 |
+
- Demo: pure python demos
|
| 15 |
+
|
| 16 |
+
- IPythonDemo: demos with input to be processed by IPython as if it had been
|
| 17 |
+
typed interactively (so magics work, as well as any other special syntax you
|
| 18 |
+
may have added via input prefilters).
|
| 19 |
+
|
| 20 |
+
- LineDemo: single-line version of the Demo class. These demos are executed
|
| 21 |
+
one line at a time, and require no markup.
|
| 22 |
+
|
| 23 |
+
- IPythonLineDemo: IPython version of the LineDemo class (the demo is
|
| 24 |
+
executed a line at a time, but processed via IPython).
|
| 25 |
+
|
| 26 |
+
- ClearMixin: mixin to make Demo classes with less visual clutter. It
|
| 27 |
+
declares an empty marquee and a pre_cmd that clears the screen before each
|
| 28 |
+
block (see Subclassing below).
|
| 29 |
+
|
| 30 |
+
- ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo
|
| 31 |
+
classes.
|
| 32 |
+
|
| 33 |
+
Inheritance diagram:
|
| 34 |
+
|
| 35 |
+
.. inheritance-diagram:: IPython.lib.demo
|
| 36 |
+
:parts: 3
|
| 37 |
+
|
| 38 |
+
Subclassing
|
| 39 |
+
-----------
|
| 40 |
+
|
| 41 |
+
The classes here all include a few methods meant to make customization by
|
| 42 |
+
subclassing more convenient. Their docstrings below have some more details:
|
| 43 |
+
|
| 44 |
+
- highlight(): format every block and optionally highlight comments and
|
| 45 |
+
docstring content.
|
| 46 |
+
|
| 47 |
+
- marquee(): generates a marquee to provide visible on-screen markers at each
|
| 48 |
+
block start and end.
|
| 49 |
+
|
| 50 |
+
- pre_cmd(): run right before the execution of each block.
|
| 51 |
+
|
| 52 |
+
- post_cmd(): run right after the execution of each block. If the block
|
| 53 |
+
raises an exception, this is NOT called.
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
Operation
|
| 57 |
+
---------
|
| 58 |
+
|
| 59 |
+
The file is run in its own empty namespace (though you can pass it a string of
|
| 60 |
+
arguments as if in a command line environment, and it will see those as
|
| 61 |
+
sys.argv). But at each stop, the global IPython namespace is updated with the
|
| 62 |
+
current internal demo namespace, so you can work interactively with the data
|
| 63 |
+
accumulated so far.
|
| 64 |
+
|
| 65 |
+
By default, each block of code is printed (with syntax highlighting) before
|
| 66 |
+
executing it and you have to confirm execution. This is intended to show the
|
| 67 |
+
code to an audience first so you can discuss it, and only proceed with
|
| 68 |
+
execution once you agree. There are a few tags which allow you to modify this
|
| 69 |
+
behavior.
|
| 70 |
+
|
| 71 |
+
The supported tags are:
|
| 72 |
+
|
| 73 |
+
# <demo> stop
|
| 74 |
+
|
| 75 |
+
Defines block boundaries, the points where IPython stops execution of the
|
| 76 |
+
file and returns to the interactive prompt.
|
| 77 |
+
|
| 78 |
+
You can optionally mark the stop tag with extra dashes before and after the
|
| 79 |
+
word 'stop', to help visually distinguish the blocks in a text editor:
|
| 80 |
+
|
| 81 |
+
# <demo> --- stop ---
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# <demo> silent
|
| 85 |
+
|
| 86 |
+
Make a block execute silently (and hence automatically). Typically used in
|
| 87 |
+
cases where you have some boilerplate or initialization code which you need
|
| 88 |
+
executed but do not want to be seen in the demo.
|
| 89 |
+
|
| 90 |
+
# <demo> auto
|
| 91 |
+
|
| 92 |
+
Make a block execute automatically, but still being printed. Useful for
|
| 93 |
+
simple code which does not warrant discussion, since it avoids the extra
|
| 94 |
+
manual confirmation.
|
| 95 |
+
|
| 96 |
+
# <demo> auto_all
|
| 97 |
+
|
| 98 |
+
This tag can _only_ be in the first block, and if given it overrides the
|
| 99 |
+
individual auto tags to make the whole demo fully automatic (no block asks
|
| 100 |
+
for confirmation). It can also be given at creation time (or the attribute
|
| 101 |
+
set later) to override what's in the file.
|
| 102 |
+
|
| 103 |
+
While _any_ python file can be run as a Demo instance, if there are no stop
|
| 104 |
+
tags the whole file will run in a single block (no different that calling
|
| 105 |
+
first %pycat and then %run). The minimal markup to make this useful is to
|
| 106 |
+
place a set of stop tags; the other tags are only there to let you fine-tune
|
| 107 |
+
the execution.
|
| 108 |
+
|
| 109 |
+
This is probably best explained with the simple example file below. You can
|
| 110 |
+
copy this into a file named ex_demo.py, and try running it via::
|
| 111 |
+
|
| 112 |
+
from IPython.lib.demo import Demo
|
| 113 |
+
d = Demo('ex_demo.py')
|
| 114 |
+
d()
|
| 115 |
+
|
| 116 |
+
Each time you call the demo object, it runs the next block. The demo object
|
| 117 |
+
has a few useful methods for navigation, like again(), edit(), jump(), seek()
|
| 118 |
+
and back(). It can be reset for a new run via reset() or reloaded from disk
|
| 119 |
+
(in case you've edited the source) via reload(). See their docstrings below.
|
| 120 |
+
|
| 121 |
+
Note: To make this simpler to explore, a file called "demo-exercizer.py" has
|
| 122 |
+
been added to the "docs/examples/core" directory. Just cd to this directory in
|
| 123 |
+
an IPython session, and type::
|
| 124 |
+
|
| 125 |
+
%run demo-exercizer.py
|
| 126 |
+
|
| 127 |
+
and then follow the directions.
|
| 128 |
+
|
| 129 |
+
Example
|
| 130 |
+
-------
|
| 131 |
+
|
| 132 |
+
The following is a very simple example of a valid demo file.
|
| 133 |
+
|
| 134 |
+
::
|
| 135 |
+
|
| 136 |
+
#################### EXAMPLE DEMO <ex_demo.py> ###############################
|
| 137 |
+
'''A simple interactive demo to illustrate the use of IPython's Demo class.'''
|
| 138 |
+
|
| 139 |
+
print('Hello, welcome to an interactive IPython demo.')
|
| 140 |
+
|
| 141 |
+
# The mark below defines a block boundary, which is a point where IPython will
|
| 142 |
+
# stop execution and return to the interactive prompt. The dashes are actually
|
| 143 |
+
# optional and used only as a visual aid to clearly separate blocks while
|
| 144 |
+
# editing the demo code.
|
| 145 |
+
# <demo> stop
|
| 146 |
+
|
| 147 |
+
x = 1
|
| 148 |
+
y = 2
|
| 149 |
+
|
| 150 |
+
# <demo> stop
|
| 151 |
+
|
| 152 |
+
# the mark below makes this block as silent
|
| 153 |
+
# <demo> silent
|
| 154 |
+
|
| 155 |
+
print('This is a silent block, which gets executed but not printed.')
|
| 156 |
+
|
| 157 |
+
# <demo> stop
|
| 158 |
+
# <demo> auto
|
| 159 |
+
print('This is an automatic block.')
|
| 160 |
+
print('It is executed without asking for confirmation, but printed.')
|
| 161 |
+
z = x + y
|
| 162 |
+
|
| 163 |
+
print('z =', x)
|
| 164 |
+
|
| 165 |
+
# <demo> stop
|
| 166 |
+
# This is just another normal block.
|
| 167 |
+
print('z is now:', z)
|
| 168 |
+
|
| 169 |
+
print('bye!')
|
| 170 |
+
################### END EXAMPLE DEMO <ex_demo.py> ############################
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
#*****************************************************************************
|
| 175 |
+
# Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu>
|
| 176 |
+
#
|
| 177 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 178 |
+
# the file COPYING, distributed as part of this software.
|
| 179 |
+
#
|
| 180 |
+
#*****************************************************************************
|
| 181 |
+
|
| 182 |
+
import os
|
| 183 |
+
import re
|
| 184 |
+
import shlex
|
| 185 |
+
import sys
|
| 186 |
+
import pygments
|
| 187 |
+
from pathlib import Path
|
| 188 |
+
|
| 189 |
+
from IPython.utils.text import marquee
|
| 190 |
+
from IPython.utils import openpy
|
| 191 |
+
from IPython.utils import py3compat
|
| 192 |
+
__all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError']
|
| 193 |
+
|
| 194 |
+
class DemoError(Exception): pass
|
| 195 |
+
|
| 196 |
+
def re_mark(mark):
|
| 197 |
+
return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE)
|
| 198 |
+
|
| 199 |
+
class Demo(object):
|
| 200 |
+
|
| 201 |
+
re_stop = re_mark(r'-*\s?stop\s?-*')
|
| 202 |
+
re_silent = re_mark('silent')
|
| 203 |
+
re_auto = re_mark('auto')
|
| 204 |
+
re_auto_all = re_mark('auto_all')
|
| 205 |
+
|
| 206 |
+
def __init__(self,src,title='',arg_str='',auto_all=None, format_rst=False,
|
| 207 |
+
formatter='terminal', style='default'):
|
| 208 |
+
"""Make a new demo object. To run the demo, simply call the object.
|
| 209 |
+
|
| 210 |
+
See the module docstring for full details and an example (you can use
|
| 211 |
+
IPython.Demo? in IPython to see it).
|
| 212 |
+
|
| 213 |
+
Inputs:
|
| 214 |
+
|
| 215 |
+
- src is either a file, or file-like object, or a
|
| 216 |
+
string that can be resolved to a filename.
|
| 217 |
+
|
| 218 |
+
Optional inputs:
|
| 219 |
+
|
| 220 |
+
- title: a string to use as the demo name. Of most use when the demo
|
| 221 |
+
you are making comes from an object that has no filename, or if you
|
| 222 |
+
want an alternate denotation distinct from the filename.
|
| 223 |
+
|
| 224 |
+
- arg_str(''): a string of arguments, internally converted to a list
|
| 225 |
+
just like sys.argv, so the demo script can see a similar
|
| 226 |
+
environment.
|
| 227 |
+
|
| 228 |
+
- auto_all(None): global flag to run all blocks automatically without
|
| 229 |
+
confirmation. This attribute overrides the block-level tags and
|
| 230 |
+
applies to the whole demo. It is an attribute of the object, and
|
| 231 |
+
can be changed at runtime simply by reassigning it to a boolean
|
| 232 |
+
value.
|
| 233 |
+
|
| 234 |
+
- format_rst(False): a bool to enable comments and doc strings
|
| 235 |
+
formatting with pygments rst lexer
|
| 236 |
+
|
| 237 |
+
- formatter('terminal'): a string of pygments formatter name to be
|
| 238 |
+
used. Useful values for terminals: terminal, terminal256,
|
| 239 |
+
terminal16m
|
| 240 |
+
|
| 241 |
+
- style('default'): a string of pygments style name to be used.
|
| 242 |
+
"""
|
| 243 |
+
if hasattr(src, "read"):
|
| 244 |
+
# It seems to be a file or a file-like object
|
| 245 |
+
self.fname = "from a file-like object"
|
| 246 |
+
if title == '':
|
| 247 |
+
self.title = "from a file-like object"
|
| 248 |
+
else:
|
| 249 |
+
self.title = title
|
| 250 |
+
else:
|
| 251 |
+
# Assume it's a string or something that can be converted to one
|
| 252 |
+
self.fname = src
|
| 253 |
+
if title == '':
|
| 254 |
+
(filepath, filename) = os.path.split(src)
|
| 255 |
+
self.title = filename
|
| 256 |
+
else:
|
| 257 |
+
self.title = title
|
| 258 |
+
self.sys_argv = [src] + shlex.split(arg_str)
|
| 259 |
+
self.auto_all = auto_all
|
| 260 |
+
self.src = src
|
| 261 |
+
|
| 262 |
+
try:
|
| 263 |
+
ip = get_ipython() # this is in builtins whenever IPython is running
|
| 264 |
+
self.inside_ipython = True
|
| 265 |
+
except NameError:
|
| 266 |
+
self.inside_ipython = False
|
| 267 |
+
|
| 268 |
+
if self.inside_ipython:
|
| 269 |
+
# get a few things from ipython. While it's a bit ugly design-wise,
|
| 270 |
+
# it ensures that things like color scheme and the like are always in
|
| 271 |
+
# sync with the ipython mode being used. This class is only meant to
|
| 272 |
+
# be used inside ipython anyways, so it's OK.
|
| 273 |
+
self.ip_ns = ip.user_ns
|
| 274 |
+
self.ip_colorize = ip.pycolorize
|
| 275 |
+
self.ip_showtb = ip.showtraceback
|
| 276 |
+
self.ip_run_cell = ip.run_cell
|
| 277 |
+
self.shell = ip
|
| 278 |
+
|
| 279 |
+
self.formatter = pygments.formatters.get_formatter_by_name(formatter,
|
| 280 |
+
style=style)
|
| 281 |
+
self.python_lexer = pygments.lexers.get_lexer_by_name("py3")
|
| 282 |
+
self.format_rst = format_rst
|
| 283 |
+
if format_rst:
|
| 284 |
+
self.rst_lexer = pygments.lexers.get_lexer_by_name("rst")
|
| 285 |
+
|
| 286 |
+
# load user data and initialize data structures
|
| 287 |
+
self.reload()
|
| 288 |
+
|
| 289 |
+
def fload(self):
|
| 290 |
+
"""Load file object."""
|
| 291 |
+
# read data and parse into blocks
|
| 292 |
+
if hasattr(self, 'fobj') and self.fobj is not None:
|
| 293 |
+
self.fobj.close()
|
| 294 |
+
if hasattr(self.src, "read"):
|
| 295 |
+
# It seems to be a file or a file-like object
|
| 296 |
+
self.fobj = self.src
|
| 297 |
+
else:
|
| 298 |
+
# Assume it's a string or something that can be converted to one
|
| 299 |
+
self.fobj = openpy.open(self.fname)
|
| 300 |
+
|
| 301 |
+
def reload(self):
|
| 302 |
+
"""Reload source from disk and initialize state."""
|
| 303 |
+
self.fload()
|
| 304 |
+
|
| 305 |
+
self.src = "".join(openpy.strip_encoding_cookie(self.fobj))
|
| 306 |
+
src_b = [b.strip() for b in self.re_stop.split(self.src) if b]
|
| 307 |
+
self._silent = [bool(self.re_silent.findall(b)) for b in src_b]
|
| 308 |
+
self._auto = [bool(self.re_auto.findall(b)) for b in src_b]
|
| 309 |
+
|
| 310 |
+
# if auto_all is not given (def. None), we read it from the file
|
| 311 |
+
if self.auto_all is None:
|
| 312 |
+
self.auto_all = bool(self.re_auto_all.findall(src_b[0]))
|
| 313 |
+
else:
|
| 314 |
+
self.auto_all = bool(self.auto_all)
|
| 315 |
+
|
| 316 |
+
# Clean the sources from all markup so it doesn't get displayed when
|
| 317 |
+
# running the demo
|
| 318 |
+
src_blocks = []
|
| 319 |
+
auto_strip = lambda s: self.re_auto.sub('',s)
|
| 320 |
+
for i,b in enumerate(src_b):
|
| 321 |
+
if self._auto[i]:
|
| 322 |
+
src_blocks.append(auto_strip(b))
|
| 323 |
+
else:
|
| 324 |
+
src_blocks.append(b)
|
| 325 |
+
# remove the auto_all marker
|
| 326 |
+
src_blocks[0] = self.re_auto_all.sub('',src_blocks[0])
|
| 327 |
+
|
| 328 |
+
self.nblocks = len(src_blocks)
|
| 329 |
+
self.src_blocks = src_blocks
|
| 330 |
+
|
| 331 |
+
# also build syntax-highlighted source
|
| 332 |
+
self.src_blocks_colored = list(map(self.highlight,self.src_blocks))
|
| 333 |
+
|
| 334 |
+
# ensure clean namespace and seek offset
|
| 335 |
+
self.reset()
|
| 336 |
+
|
| 337 |
+
def reset(self):
|
| 338 |
+
"""Reset the namespace and seek pointer to restart the demo"""
|
| 339 |
+
self.user_ns = {}
|
| 340 |
+
self.finished = False
|
| 341 |
+
self.block_index = 0
|
| 342 |
+
|
| 343 |
+
def _validate_index(self,index):
|
| 344 |
+
if index<0 or index>=self.nblocks:
|
| 345 |
+
raise ValueError('invalid block index %s' % index)
|
| 346 |
+
|
| 347 |
+
def _get_index(self,index):
|
| 348 |
+
"""Get the current block index, validating and checking status.
|
| 349 |
+
|
| 350 |
+
Returns None if the demo is finished"""
|
| 351 |
+
|
| 352 |
+
if index is None:
|
| 353 |
+
if self.finished:
|
| 354 |
+
print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
|
| 355 |
+
return None
|
| 356 |
+
index = self.block_index
|
| 357 |
+
else:
|
| 358 |
+
self._validate_index(index)
|
| 359 |
+
return index
|
| 360 |
+
|
| 361 |
+
def seek(self,index):
|
| 362 |
+
"""Move the current seek pointer to the given block.
|
| 363 |
+
|
| 364 |
+
You can use negative indices to seek from the end, with identical
|
| 365 |
+
semantics to those of Python lists."""
|
| 366 |
+
if index<0:
|
| 367 |
+
index = self.nblocks + index
|
| 368 |
+
self._validate_index(index)
|
| 369 |
+
self.block_index = index
|
| 370 |
+
self.finished = False
|
| 371 |
+
|
| 372 |
+
def back(self,num=1):
|
| 373 |
+
"""Move the seek pointer back num blocks (default is 1)."""
|
| 374 |
+
self.seek(self.block_index-num)
|
| 375 |
+
|
| 376 |
+
def jump(self,num=1):
|
| 377 |
+
"""Jump a given number of blocks relative to the current one.
|
| 378 |
+
|
| 379 |
+
The offset can be positive or negative, defaults to 1."""
|
| 380 |
+
self.seek(self.block_index+num)
|
| 381 |
+
|
| 382 |
+
def again(self):
|
| 383 |
+
"""Move the seek pointer back one block and re-execute."""
|
| 384 |
+
self.back(1)
|
| 385 |
+
self()
|
| 386 |
+
|
| 387 |
+
def edit(self,index=None):
|
| 388 |
+
"""Edit a block.
|
| 389 |
+
|
| 390 |
+
If no number is given, use the last block executed.
|
| 391 |
+
|
| 392 |
+
This edits the in-memory copy of the demo, it does NOT modify the
|
| 393 |
+
original source file. If you want to do that, simply open the file in
|
| 394 |
+
an editor and use reload() when you make changes to the file. This
|
| 395 |
+
method is meant to let you change a block during a demonstration for
|
| 396 |
+
explanatory purposes, without damaging your original script."""
|
| 397 |
+
|
| 398 |
+
index = self._get_index(index)
|
| 399 |
+
if index is None:
|
| 400 |
+
return
|
| 401 |
+
# decrease the index by one (unless we're at the very beginning), so
|
| 402 |
+
# that the default demo.edit() call opens up the sblock we've last run
|
| 403 |
+
if index>0:
|
| 404 |
+
index -= 1
|
| 405 |
+
|
| 406 |
+
filename = self.shell.mktempfile(self.src_blocks[index])
|
| 407 |
+
self.shell.hooks.editor(filename, 1)
|
| 408 |
+
with open(Path(filename), "r", encoding="utf-8") as f:
|
| 409 |
+
new_block = f.read()
|
| 410 |
+
# update the source and colored block
|
| 411 |
+
self.src_blocks[index] = new_block
|
| 412 |
+
self.src_blocks_colored[index] = self.highlight(new_block)
|
| 413 |
+
self.block_index = index
|
| 414 |
+
# call to run with the newly edited index
|
| 415 |
+
self()
|
| 416 |
+
|
| 417 |
+
def show(self,index=None):
|
| 418 |
+
"""Show a single block on screen"""
|
| 419 |
+
|
| 420 |
+
index = self._get_index(index)
|
| 421 |
+
if index is None:
|
| 422 |
+
return
|
| 423 |
+
|
| 424 |
+
print(self.marquee('<%s> block # %s (%s remaining)' %
|
| 425 |
+
(self.title,index,self.nblocks-index-1)))
|
| 426 |
+
print(self.src_blocks_colored[index])
|
| 427 |
+
sys.stdout.flush()
|
| 428 |
+
|
| 429 |
+
def show_all(self):
|
| 430 |
+
"""Show entire demo on screen, block by block"""
|
| 431 |
+
|
| 432 |
+
fname = self.title
|
| 433 |
+
title = self.title
|
| 434 |
+
nblocks = self.nblocks
|
| 435 |
+
silent = self._silent
|
| 436 |
+
marquee = self.marquee
|
| 437 |
+
for index,block in enumerate(self.src_blocks_colored):
|
| 438 |
+
if silent[index]:
|
| 439 |
+
print(marquee('<%s> SILENT block # %s (%s remaining)' %
|
| 440 |
+
(title,index,nblocks-index-1)))
|
| 441 |
+
else:
|
| 442 |
+
print(marquee('<%s> block # %s (%s remaining)' %
|
| 443 |
+
(title,index,nblocks-index-1)))
|
| 444 |
+
print(block, end=' ')
|
| 445 |
+
sys.stdout.flush()
|
| 446 |
+
|
| 447 |
+
def run_cell(self,source):
|
| 448 |
+
"""Execute a string with one or more lines of code"""
|
| 449 |
+
|
| 450 |
+
exec(source, self.user_ns)
|
| 451 |
+
|
| 452 |
+
def __call__(self,index=None):
|
| 453 |
+
"""run a block of the demo.
|
| 454 |
+
|
| 455 |
+
If index is given, it should be an integer >=1 and <= nblocks. This
|
| 456 |
+
means that the calling convention is one off from typical Python
|
| 457 |
+
lists. The reason for the inconsistency is that the demo always
|
| 458 |
+
prints 'Block n/N, and N is the total, so it would be very odd to use
|
| 459 |
+
zero-indexing here."""
|
| 460 |
+
|
| 461 |
+
index = self._get_index(index)
|
| 462 |
+
if index is None:
|
| 463 |
+
return
|
| 464 |
+
try:
|
| 465 |
+
marquee = self.marquee
|
| 466 |
+
next_block = self.src_blocks[index]
|
| 467 |
+
self.block_index += 1
|
| 468 |
+
if self._silent[index]:
|
| 469 |
+
print(marquee('Executing silent block # %s (%s remaining)' %
|
| 470 |
+
(index,self.nblocks-index-1)))
|
| 471 |
+
else:
|
| 472 |
+
self.pre_cmd()
|
| 473 |
+
self.show(index)
|
| 474 |
+
if self.auto_all or self._auto[index]:
|
| 475 |
+
print(marquee('output:'))
|
| 476 |
+
else:
|
| 477 |
+
print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
|
| 478 |
+
ans = py3compat.input().strip()
|
| 479 |
+
if ans:
|
| 480 |
+
print(marquee('Block NOT executed'))
|
| 481 |
+
return
|
| 482 |
+
try:
|
| 483 |
+
save_argv = sys.argv
|
| 484 |
+
sys.argv = self.sys_argv
|
| 485 |
+
self.run_cell(next_block)
|
| 486 |
+
self.post_cmd()
|
| 487 |
+
finally:
|
| 488 |
+
sys.argv = save_argv
|
| 489 |
+
|
| 490 |
+
except:
|
| 491 |
+
if self.inside_ipython:
|
| 492 |
+
self.ip_showtb(filename=self.fname)
|
| 493 |
+
else:
|
| 494 |
+
if self.inside_ipython:
|
| 495 |
+
self.ip_ns.update(self.user_ns)
|
| 496 |
+
|
| 497 |
+
if self.block_index == self.nblocks:
|
| 498 |
+
mq1 = self.marquee('END OF DEMO')
|
| 499 |
+
if mq1:
|
| 500 |
+
# avoid spurious print if empty marquees are used
|
| 501 |
+
print()
|
| 502 |
+
print(mq1)
|
| 503 |
+
print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
|
| 504 |
+
self.finished = True
|
| 505 |
+
|
| 506 |
+
# These methods are meant to be overridden by subclasses who may wish to
|
| 507 |
+
# customize the behavior of of their demos.
|
| 508 |
+
def marquee(self,txt='',width=78,mark='*'):
|
| 509 |
+
"""Return the input string centered in a 'marquee'."""
|
| 510 |
+
return marquee(txt,width,mark)
|
| 511 |
+
|
| 512 |
+
def pre_cmd(self):
|
| 513 |
+
"""Method called before executing each block."""
|
| 514 |
+
pass
|
| 515 |
+
|
| 516 |
+
def post_cmd(self):
|
| 517 |
+
"""Method called after executing each block."""
|
| 518 |
+
pass
|
| 519 |
+
|
| 520 |
+
def highlight(self, block):
|
| 521 |
+
"""Method called on each block to highlight it content"""
|
| 522 |
+
tokens = pygments.lex(block, self.python_lexer)
|
| 523 |
+
if self.format_rst:
|
| 524 |
+
from pygments.token import Token
|
| 525 |
+
toks = []
|
| 526 |
+
for token in tokens:
|
| 527 |
+
if token[0] == Token.String.Doc and len(token[1]) > 6:
|
| 528 |
+
toks += pygments.lex(token[1][:3], self.python_lexer)
|
| 529 |
+
# parse doc string content by rst lexer
|
| 530 |
+
toks += pygments.lex(token[1][3:-3], self.rst_lexer)
|
| 531 |
+
toks += pygments.lex(token[1][-3:], self.python_lexer)
|
| 532 |
+
elif token[0] == Token.Comment.Single:
|
| 533 |
+
toks.append((Token.Comment.Single, token[1][0]))
|
| 534 |
+
# parse comment content by rst lexer
|
| 535 |
+
# remove the extra newline added by rst lexer
|
| 536 |
+
toks += list(pygments.lex(token[1][1:], self.rst_lexer))[:-1]
|
| 537 |
+
else:
|
| 538 |
+
toks.append(token)
|
| 539 |
+
tokens = toks
|
| 540 |
+
return pygments.format(tokens, self.formatter)
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
class IPythonDemo(Demo):
|
| 544 |
+
"""Class for interactive demos with IPython's input processing applied.
|
| 545 |
+
|
| 546 |
+
This subclasses Demo, but instead of executing each block by the Python
|
| 547 |
+
interpreter (via exec), it actually calls IPython on it, so that any input
|
| 548 |
+
filters which may be in place are applied to the input block.
|
| 549 |
+
|
| 550 |
+
If you have an interactive environment which exposes special input
|
| 551 |
+
processing, you can use this class instead to write demo scripts which
|
| 552 |
+
operate exactly as if you had typed them interactively. The default Demo
|
| 553 |
+
class requires the input to be valid, pure Python code.
|
| 554 |
+
"""
|
| 555 |
+
|
| 556 |
+
def run_cell(self,source):
|
| 557 |
+
"""Execute a string with one or more lines of code"""
|
| 558 |
+
|
| 559 |
+
self.shell.run_cell(source)
|
| 560 |
+
|
| 561 |
+
class LineDemo(Demo):
|
| 562 |
+
"""Demo where each line is executed as a separate block.
|
| 563 |
+
|
| 564 |
+
The input script should be valid Python code.
|
| 565 |
+
|
| 566 |
+
This class doesn't require any markup at all, and it's meant for simple
|
| 567 |
+
scripts (with no nesting or any kind of indentation) which consist of
|
| 568 |
+
multiple lines of input to be executed, one at a time, as if they had been
|
| 569 |
+
typed in the interactive prompt.
|
| 570 |
+
|
| 571 |
+
Note: the input can not have *any* indentation, which means that only
|
| 572 |
+
single-lines of input are accepted, not even function definitions are
|
| 573 |
+
valid."""
|
| 574 |
+
|
| 575 |
+
def reload(self):
|
| 576 |
+
"""Reload source from disk and initialize state."""
|
| 577 |
+
# read data and parse into blocks
|
| 578 |
+
self.fload()
|
| 579 |
+
lines = self.fobj.readlines()
|
| 580 |
+
src_b = [l for l in lines if l.strip()]
|
| 581 |
+
nblocks = len(src_b)
|
| 582 |
+
self.src = ''.join(lines)
|
| 583 |
+
self._silent = [False]*nblocks
|
| 584 |
+
self._auto = [True]*nblocks
|
| 585 |
+
self.auto_all = True
|
| 586 |
+
self.nblocks = nblocks
|
| 587 |
+
self.src_blocks = src_b
|
| 588 |
+
|
| 589 |
+
# also build syntax-highlighted source
|
| 590 |
+
self.src_blocks_colored = list(map(self.highlight,self.src_blocks))
|
| 591 |
+
|
| 592 |
+
# ensure clean namespace and seek offset
|
| 593 |
+
self.reset()
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
class IPythonLineDemo(IPythonDemo,LineDemo):
|
| 597 |
+
"""Variant of the LineDemo class whose input is processed by IPython."""
|
| 598 |
+
pass
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class ClearMixin(object):
|
| 602 |
+
"""Use this mixin to make Demo classes with less visual clutter.
|
| 603 |
+
|
| 604 |
+
Demos using this mixin will clear the screen before every block and use
|
| 605 |
+
blank marquees.
|
| 606 |
+
|
| 607 |
+
Note that in order for the methods defined here to actually override those
|
| 608 |
+
of the classes it's mixed with, it must go /first/ in the inheritance
|
| 609 |
+
tree. For example:
|
| 610 |
+
|
| 611 |
+
class ClearIPDemo(ClearMixin,IPythonDemo): pass
|
| 612 |
+
|
| 613 |
+
will provide an IPythonDemo class with the mixin's features.
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
def marquee(self,txt='',width=78,mark='*'):
|
| 617 |
+
"""Blank marquee that returns '' no matter what the input."""
|
| 618 |
+
return ''
|
| 619 |
+
|
| 620 |
+
def pre_cmd(self):
|
| 621 |
+
"""Method called before executing each block.
|
| 622 |
+
|
| 623 |
+
This one simply clears the screen."""
|
| 624 |
+
from IPython.utils.terminal import _term_clear
|
| 625 |
+
_term_clear()
|
| 626 |
+
|
| 627 |
+
class ClearDemo(ClearMixin,Demo):
|
| 628 |
+
pass
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class ClearIPDemo(ClearMixin,IPythonDemo):
|
| 632 |
+
pass
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def slide(file_path, noclear=False, format_rst=True, formatter="terminal",
|
| 636 |
+
style="native", auto_all=False, delimiter='...'):
|
| 637 |
+
if noclear:
|
| 638 |
+
demo_class = Demo
|
| 639 |
+
else:
|
| 640 |
+
demo_class = ClearDemo
|
| 641 |
+
demo = demo_class(file_path, format_rst=format_rst, formatter=formatter,
|
| 642 |
+
style=style, auto_all=auto_all)
|
| 643 |
+
while not demo.finished:
|
| 644 |
+
demo()
|
| 645 |
+
try:
|
| 646 |
+
py3compat.input('\n' + delimiter)
|
| 647 |
+
except KeyboardInterrupt:
|
| 648 |
+
exit(1)
|
| 649 |
+
|
| 650 |
+
if __name__ == '__main__':
|
| 651 |
+
import argparse
|
| 652 |
+
parser = argparse.ArgumentParser(description='Run python demos')
|
| 653 |
+
parser.add_argument('--noclear', '-C', action='store_true',
|
| 654 |
+
help='Do not clear terminal on each slide')
|
| 655 |
+
parser.add_argument('--rst', '-r', action='store_true',
|
| 656 |
+
help='Highlight comments and dostrings as rst')
|
| 657 |
+
parser.add_argument('--formatter', '-f', default='terminal',
|
| 658 |
+
help='pygments formatter name could be: terminal, '
|
| 659 |
+
'terminal256, terminal16m')
|
| 660 |
+
parser.add_argument('--style', '-s', default='default',
|
| 661 |
+
help='pygments style name')
|
| 662 |
+
parser.add_argument('--auto', '-a', action='store_true',
|
| 663 |
+
help='Run all blocks automatically without'
|
| 664 |
+
'confirmation')
|
| 665 |
+
parser.add_argument('--delimiter', '-d', default='...',
|
| 666 |
+
help='slides delimiter added after each slide run')
|
| 667 |
+
parser.add_argument('file', nargs=1,
|
| 668 |
+
help='python demo file')
|
| 669 |
+
args = parser.parse_args()
|
| 670 |
+
slide(args.file[0], noclear=args.noclear, format_rst=args.rst,
|
| 671 |
+
formatter=args.formatter, style=args.style, auto_all=args.auto,
|
| 672 |
+
delimiter=args.delimiter)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/display.py
ADDED
|
@@ -0,0 +1,677 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Various display related classes.
|
| 2 |
+
|
| 3 |
+
Authors : MinRK, gregcaporaso, dannystaple
|
| 4 |
+
"""
|
| 5 |
+
from html import escape as html_escape
|
| 6 |
+
from os.path import exists, isfile, splitext, abspath, join, isdir
|
| 7 |
+
from os import walk, sep, fsdecode
|
| 8 |
+
|
| 9 |
+
from IPython.core.display import DisplayObject, TextDisplayObject
|
| 10 |
+
|
| 11 |
+
from typing import Tuple, Iterable, Optional
|
| 12 |
+
|
| 13 |
+
__all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument',
|
| 14 |
+
'FileLink', 'FileLinks', 'Code']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Audio(DisplayObject):
|
| 18 |
+
"""Create an audio object.
|
| 19 |
+
|
| 20 |
+
When this object is returned by an input cell or passed to the
|
| 21 |
+
display function, it will result in Audio controls being displayed
|
| 22 |
+
in the frontend (only works in the notebook).
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
----------
|
| 26 |
+
data : numpy array, list, unicode, str or bytes
|
| 27 |
+
Can be one of
|
| 28 |
+
|
| 29 |
+
* Numpy 1d array containing the desired waveform (mono)
|
| 30 |
+
* Numpy 2d array containing waveforms for each channel.
|
| 31 |
+
Shape=(NCHAN, NSAMPLES). For the standard channel order, see
|
| 32 |
+
http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
|
| 33 |
+
* List of float or integer representing the waveform (mono)
|
| 34 |
+
* String containing the filename
|
| 35 |
+
* Bytestring containing raw PCM data or
|
| 36 |
+
* URL pointing to a file on the web.
|
| 37 |
+
|
| 38 |
+
If the array option is used, the waveform will be normalized.
|
| 39 |
+
|
| 40 |
+
If a filename or url is used, the format support will be browser
|
| 41 |
+
dependent.
|
| 42 |
+
url : unicode
|
| 43 |
+
A URL to download the data from.
|
| 44 |
+
filename : unicode
|
| 45 |
+
Path to a local file to load the data from.
|
| 46 |
+
embed : boolean
|
| 47 |
+
Should the audio data be embedded using a data URI (True) or should
|
| 48 |
+
the original source be referenced. Set this to True if you want the
|
| 49 |
+
audio to playable later with no internet connection in the notebook.
|
| 50 |
+
|
| 51 |
+
Default is `True`, unless the keyword argument `url` is set, then
|
| 52 |
+
default value is `False`.
|
| 53 |
+
rate : integer
|
| 54 |
+
The sampling rate of the raw data.
|
| 55 |
+
Only required when data parameter is being used as an array
|
| 56 |
+
autoplay : bool
|
| 57 |
+
Set to True if the audio should immediately start playing.
|
| 58 |
+
Default is `False`.
|
| 59 |
+
normalize : bool
|
| 60 |
+
Whether audio should be normalized (rescaled) to the maximum possible
|
| 61 |
+
range. Default is `True`. When set to `False`, `data` must be between
|
| 62 |
+
-1 and 1 (inclusive), otherwise an error is raised.
|
| 63 |
+
Applies only when `data` is a list or array of samples; other types of
|
| 64 |
+
audio are never normalized.
|
| 65 |
+
|
| 66 |
+
Examples
|
| 67 |
+
--------
|
| 68 |
+
|
| 69 |
+
>>> import pytest
|
| 70 |
+
>>> np = pytest.importorskip("numpy")
|
| 71 |
+
|
| 72 |
+
Generate a sound
|
| 73 |
+
|
| 74 |
+
>>> import numpy as np
|
| 75 |
+
>>> framerate = 44100
|
| 76 |
+
>>> t = np.linspace(0,5,framerate*5)
|
| 77 |
+
>>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
|
| 78 |
+
>>> Audio(data, rate=framerate)
|
| 79 |
+
<IPython.lib.display.Audio object>
|
| 80 |
+
|
| 81 |
+
Can also do stereo or more channels
|
| 82 |
+
|
| 83 |
+
>>> dataleft = np.sin(2*np.pi*220*t)
|
| 84 |
+
>>> dataright = np.sin(2*np.pi*224*t)
|
| 85 |
+
>>> Audio([dataleft, dataright], rate=framerate)
|
| 86 |
+
<IPython.lib.display.Audio object>
|
| 87 |
+
|
| 88 |
+
From URL:
|
| 89 |
+
|
| 90 |
+
>>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP
|
| 91 |
+
>>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP
|
| 92 |
+
|
| 93 |
+
From a File:
|
| 94 |
+
|
| 95 |
+
>>> Audio('IPython/lib/tests/test.wav') # doctest: +SKIP
|
| 96 |
+
>>> Audio(filename='IPython/lib/tests/test.wav') # doctest: +SKIP
|
| 97 |
+
|
| 98 |
+
From Bytes:
|
| 99 |
+
|
| 100 |
+
>>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP
|
| 101 |
+
>>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP
|
| 102 |
+
|
| 103 |
+
See Also
|
| 104 |
+
--------
|
| 105 |
+
ipywidgets.Audio
|
| 106 |
+
|
| 107 |
+
Audio widget with more more flexibility and options.
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
_read_flags = 'rb'
|
| 111 |
+
|
| 112 |
+
def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *,
|
| 113 |
+
element_id=None):
|
| 114 |
+
if filename is None and url is None and data is None:
|
| 115 |
+
raise ValueError("No audio data found. Expecting filename, url, or data.")
|
| 116 |
+
if embed is False and url is None:
|
| 117 |
+
raise ValueError("No url found. Expecting url when embed=False")
|
| 118 |
+
|
| 119 |
+
if url is not None and embed is not True:
|
| 120 |
+
self.embed = False
|
| 121 |
+
else:
|
| 122 |
+
self.embed = True
|
| 123 |
+
self.autoplay = autoplay
|
| 124 |
+
self.element_id = element_id
|
| 125 |
+
super(Audio, self).__init__(data=data, url=url, filename=filename)
|
| 126 |
+
|
| 127 |
+
if self.data is not None and not isinstance(self.data, bytes):
|
| 128 |
+
if rate is None:
|
| 129 |
+
raise ValueError("rate must be specified when data is a numpy array or list of audio samples.")
|
| 130 |
+
self.data = Audio._make_wav(data, rate, normalize)
|
| 131 |
+
|
| 132 |
+
def reload(self):
|
| 133 |
+
"""Reload the raw data from file or URL."""
|
| 134 |
+
import mimetypes
|
| 135 |
+
if self.embed:
|
| 136 |
+
super(Audio, self).reload()
|
| 137 |
+
|
| 138 |
+
if self.filename is not None:
|
| 139 |
+
self.mimetype = mimetypes.guess_type(self.filename)[0]
|
| 140 |
+
elif self.url is not None:
|
| 141 |
+
self.mimetype = mimetypes.guess_type(self.url)[0]
|
| 142 |
+
else:
|
| 143 |
+
self.mimetype = "audio/wav"
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def _make_wav(data, rate, normalize):
|
| 147 |
+
""" Transform a numpy array to a PCM bytestring """
|
| 148 |
+
from io import BytesIO
|
| 149 |
+
import wave
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize)
|
| 153 |
+
except ImportError:
|
| 154 |
+
scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize)
|
| 155 |
+
|
| 156 |
+
fp = BytesIO()
|
| 157 |
+
waveobj = wave.open(fp,mode='wb')
|
| 158 |
+
waveobj.setnchannels(nchan)
|
| 159 |
+
waveobj.setframerate(rate)
|
| 160 |
+
waveobj.setsampwidth(2)
|
| 161 |
+
waveobj.setcomptype('NONE','NONE')
|
| 162 |
+
waveobj.writeframes(scaled)
|
| 163 |
+
val = fp.getvalue()
|
| 164 |
+
waveobj.close()
|
| 165 |
+
|
| 166 |
+
return val
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]:
|
| 170 |
+
import numpy as np
|
| 171 |
+
|
| 172 |
+
data = np.array(data, dtype=float)
|
| 173 |
+
if len(data.shape) == 1:
|
| 174 |
+
nchan = 1
|
| 175 |
+
elif len(data.shape) == 2:
|
| 176 |
+
# In wave files,channels are interleaved. E.g.,
|
| 177 |
+
# "L1R1L2R2..." for stereo. See
|
| 178 |
+
# http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
|
| 179 |
+
# for channel ordering
|
| 180 |
+
nchan = data.shape[0]
|
| 181 |
+
data = data.T.ravel()
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError('Array audio input must be a 1D or 2D array')
|
| 184 |
+
|
| 185 |
+
max_abs_value = np.max(np.abs(data))
|
| 186 |
+
normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
|
| 187 |
+
scaled = data / normalization_factor * 32767
|
| 188 |
+
return scaled.astype("<h").tobytes(), nchan
|
| 189 |
+
|
| 190 |
+
@staticmethod
|
| 191 |
+
def _validate_and_normalize_without_numpy(data, normalize):
|
| 192 |
+
import array
|
| 193 |
+
import sys
|
| 194 |
+
|
| 195 |
+
data = array.array('f', data)
|
| 196 |
+
|
| 197 |
+
try:
|
| 198 |
+
max_abs_value = float(max([abs(x) for x in data]))
|
| 199 |
+
except TypeError as e:
|
| 200 |
+
raise TypeError('Only lists of mono audio are '
|
| 201 |
+
'supported if numpy is not installed') from e
|
| 202 |
+
|
| 203 |
+
normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
|
| 204 |
+
scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data])
|
| 205 |
+
if sys.byteorder == 'big':
|
| 206 |
+
scaled.byteswap()
|
| 207 |
+
nchan = 1
|
| 208 |
+
return scaled.tobytes(), nchan
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def _get_normalization_factor(max_abs_value, normalize):
|
| 212 |
+
if not normalize and max_abs_value > 1:
|
| 213 |
+
raise ValueError('Audio data must be between -1 and 1 when normalize=False.')
|
| 214 |
+
return max_abs_value if normalize else 1
|
| 215 |
+
|
| 216 |
+
def _data_and_metadata(self):
|
| 217 |
+
"""shortcut for returning metadata with url information, if defined"""
|
| 218 |
+
md = {}
|
| 219 |
+
if self.url:
|
| 220 |
+
md['url'] = self.url
|
| 221 |
+
if md:
|
| 222 |
+
return self.data, md
|
| 223 |
+
else:
|
| 224 |
+
return self.data
|
| 225 |
+
|
| 226 |
+
def _repr_html_(self):
|
| 227 |
+
src = """
|
| 228 |
+
<audio {element_id} controls="controls" {autoplay}>
|
| 229 |
+
<source src="{src}" type="{type}" />
|
| 230 |
+
Your browser does not support the audio element.
|
| 231 |
+
</audio>
|
| 232 |
+
"""
|
| 233 |
+
return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(),
|
| 234 |
+
element_id=self.element_id_attr())
|
| 235 |
+
|
| 236 |
+
def src_attr(self):
|
| 237 |
+
import base64
|
| 238 |
+
if self.embed and (self.data is not None):
|
| 239 |
+
data = base64=base64.b64encode(self.data).decode('ascii')
|
| 240 |
+
return """data:{type};base64,{base64}""".format(type=self.mimetype,
|
| 241 |
+
base64=data)
|
| 242 |
+
elif self.url is not None:
|
| 243 |
+
return self.url
|
| 244 |
+
else:
|
| 245 |
+
return ""
|
| 246 |
+
|
| 247 |
+
def autoplay_attr(self):
|
| 248 |
+
if(self.autoplay):
|
| 249 |
+
return 'autoplay="autoplay"'
|
| 250 |
+
else:
|
| 251 |
+
return ''
|
| 252 |
+
|
| 253 |
+
def element_id_attr(self):
|
| 254 |
+
if (self.element_id):
|
| 255 |
+
return 'id="{element_id}"'.format(element_id=self.element_id)
|
| 256 |
+
else:
|
| 257 |
+
return ''
|
| 258 |
+
|
| 259 |
+
class IFrame(object):
|
| 260 |
+
"""
|
| 261 |
+
Generic class to embed an iframe in an IPython notebook
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
iframe = """
|
| 265 |
+
<iframe
|
| 266 |
+
width="{width}"
|
| 267 |
+
height="{height}"
|
| 268 |
+
src="{src}{params}"
|
| 269 |
+
frameborder="0"
|
| 270 |
+
allowfullscreen
|
| 271 |
+
{extras}
|
| 272 |
+
></iframe>
|
| 273 |
+
"""
|
| 274 |
+
|
| 275 |
+
def __init__(
|
| 276 |
+
self, src, width, height, extras: Optional[Iterable[str]] = None, **kwargs
|
| 277 |
+
):
|
| 278 |
+
if extras is None:
|
| 279 |
+
extras = []
|
| 280 |
+
|
| 281 |
+
self.src = src
|
| 282 |
+
self.width = width
|
| 283 |
+
self.height = height
|
| 284 |
+
self.extras = extras
|
| 285 |
+
self.params = kwargs
|
| 286 |
+
|
| 287 |
+
def _repr_html_(self):
|
| 288 |
+
"""return the embed iframe"""
|
| 289 |
+
if self.params:
|
| 290 |
+
from urllib.parse import urlencode
|
| 291 |
+
params = "?" + urlencode(self.params)
|
| 292 |
+
else:
|
| 293 |
+
params = ""
|
| 294 |
+
return self.iframe.format(
|
| 295 |
+
src=self.src,
|
| 296 |
+
width=self.width,
|
| 297 |
+
height=self.height,
|
| 298 |
+
params=params,
|
| 299 |
+
extras=" ".join(self.extras),
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class YouTubeVideo(IFrame):
|
| 304 |
+
"""Class for embedding a YouTube Video in an IPython session, based on its video id.
|
| 305 |
+
|
| 306 |
+
e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
|
| 307 |
+
do::
|
| 308 |
+
|
| 309 |
+
vid = YouTubeVideo("foo")
|
| 310 |
+
display(vid)
|
| 311 |
+
|
| 312 |
+
To start from 30 seconds::
|
| 313 |
+
|
| 314 |
+
vid = YouTubeVideo("abc", start=30)
|
| 315 |
+
display(vid)
|
| 316 |
+
|
| 317 |
+
To calculate seconds from time as hours, minutes, seconds use
|
| 318 |
+
:class:`datetime.timedelta`::
|
| 319 |
+
|
| 320 |
+
start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
|
| 321 |
+
|
| 322 |
+
Other parameters can be provided as documented at
|
| 323 |
+
https://developers.google.com/youtube/player_parameters#Parameters
|
| 324 |
+
|
| 325 |
+
When converting the notebook using nbconvert, a jpeg representation of the video
|
| 326 |
+
will be inserted in the document.
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs):
|
| 330 |
+
self.id=id
|
| 331 |
+
src = "https://www.youtube.com/embed/{0}".format(id)
|
| 332 |
+
if allow_autoplay:
|
| 333 |
+
extras = list(kwargs.get("extras", [])) + ['allow="autoplay"']
|
| 334 |
+
kwargs.update(autoplay=1, extras=extras)
|
| 335 |
+
super(YouTubeVideo, self).__init__(src, width, height, **kwargs)
|
| 336 |
+
|
| 337 |
+
def _repr_jpeg_(self):
|
| 338 |
+
# Deferred import
|
| 339 |
+
from urllib.request import urlopen
|
| 340 |
+
|
| 341 |
+
try:
|
| 342 |
+
return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
|
| 343 |
+
except IOError:
|
| 344 |
+
return None
|
| 345 |
+
|
| 346 |
+
class VimeoVideo(IFrame):
|
| 347 |
+
"""
|
| 348 |
+
Class for embedding a Vimeo video in an IPython session, based on its video id.
|
| 349 |
+
"""
|
| 350 |
+
|
| 351 |
+
def __init__(self, id, width=400, height=300, **kwargs):
|
| 352 |
+
src="https://player.vimeo.com/video/{0}".format(id)
|
| 353 |
+
super(VimeoVideo, self).__init__(src, width, height, **kwargs)
|
| 354 |
+
|
| 355 |
+
class ScribdDocument(IFrame):
|
| 356 |
+
"""
|
| 357 |
+
Class for embedding a Scribd document in an IPython session
|
| 358 |
+
|
| 359 |
+
Use the start_page params to specify a starting point in the document
|
| 360 |
+
Use the view_mode params to specify display type one off scroll | slideshow | book
|
| 361 |
+
|
| 362 |
+
e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
|
| 363 |
+
|
| 364 |
+
ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
|
| 365 |
+
"""
|
| 366 |
+
|
| 367 |
+
def __init__(self, id, width=400, height=300, **kwargs):
|
| 368 |
+
src="https://www.scribd.com/embeds/{0}/content".format(id)
|
| 369 |
+
super(ScribdDocument, self).__init__(src, width, height, **kwargs)
|
| 370 |
+
|
| 371 |
+
class FileLink(object):
|
| 372 |
+
"""Class for embedding a local file link in an IPython session, based on path
|
| 373 |
+
|
| 374 |
+
e.g. to embed a link that was generated in the IPython notebook as my/data.txt
|
| 375 |
+
|
| 376 |
+
you would do::
|
| 377 |
+
|
| 378 |
+
local_file = FileLink("my/data.txt")
|
| 379 |
+
display(local_file)
|
| 380 |
+
|
| 381 |
+
or in the HTML notebook, just::
|
| 382 |
+
|
| 383 |
+
FileLink("my/data.txt")
|
| 384 |
+
"""
|
| 385 |
+
|
| 386 |
+
html_link_str = "<a href='%s' target='_blank'>%s</a>"
|
| 387 |
+
|
| 388 |
+
def __init__(self,
|
| 389 |
+
path,
|
| 390 |
+
url_prefix='',
|
| 391 |
+
result_html_prefix='',
|
| 392 |
+
result_html_suffix='<br>'):
|
| 393 |
+
"""
|
| 394 |
+
Parameters
|
| 395 |
+
----------
|
| 396 |
+
path : str
|
| 397 |
+
path to the file or directory that should be formatted
|
| 398 |
+
url_prefix : str
|
| 399 |
+
prefix to be prepended to all files to form a working link [default:
|
| 400 |
+
'']
|
| 401 |
+
result_html_prefix : str
|
| 402 |
+
text to append to beginning to link [default: '']
|
| 403 |
+
result_html_suffix : str
|
| 404 |
+
text to append at the end of link [default: '<br>']
|
| 405 |
+
"""
|
| 406 |
+
if isdir(path):
|
| 407 |
+
raise ValueError("Cannot display a directory using FileLink. "
|
| 408 |
+
"Use FileLinks to display '%s'." % path)
|
| 409 |
+
self.path = fsdecode(path)
|
| 410 |
+
self.url_prefix = url_prefix
|
| 411 |
+
self.result_html_prefix = result_html_prefix
|
| 412 |
+
self.result_html_suffix = result_html_suffix
|
| 413 |
+
|
| 414 |
+
def _format_path(self):
|
| 415 |
+
fp = ''.join([self.url_prefix, html_escape(self.path)])
|
| 416 |
+
return ''.join([self.result_html_prefix,
|
| 417 |
+
self.html_link_str % \
|
| 418 |
+
(fp, html_escape(self.path, quote=False)),
|
| 419 |
+
self.result_html_suffix])
|
| 420 |
+
|
| 421 |
+
def _repr_html_(self):
|
| 422 |
+
"""return html link to file
|
| 423 |
+
"""
|
| 424 |
+
if not exists(self.path):
|
| 425 |
+
return ("Path (<tt>%s</tt>) doesn't exist. "
|
| 426 |
+
"It may still be in the process of "
|
| 427 |
+
"being generated, or you may have the "
|
| 428 |
+
"incorrect path." % self.path)
|
| 429 |
+
|
| 430 |
+
return self._format_path()
|
| 431 |
+
|
| 432 |
+
def __repr__(self):
|
| 433 |
+
"""return absolute path to file
|
| 434 |
+
"""
|
| 435 |
+
return abspath(self.path)
|
| 436 |
+
|
| 437 |
+
class FileLinks(FileLink):
|
| 438 |
+
"""Class for embedding local file links in an IPython session, based on path
|
| 439 |
+
|
| 440 |
+
e.g. to embed links to files that were generated in the IPython notebook
|
| 441 |
+
under ``my/data``, you would do::
|
| 442 |
+
|
| 443 |
+
local_files = FileLinks("my/data")
|
| 444 |
+
display(local_files)
|
| 445 |
+
|
| 446 |
+
or in the HTML notebook, just::
|
| 447 |
+
|
| 448 |
+
FileLinks("my/data")
|
| 449 |
+
"""
|
| 450 |
+
def __init__(self,
|
| 451 |
+
path,
|
| 452 |
+
url_prefix='',
|
| 453 |
+
included_suffixes=None,
|
| 454 |
+
result_html_prefix='',
|
| 455 |
+
result_html_suffix='<br>',
|
| 456 |
+
notebook_display_formatter=None,
|
| 457 |
+
terminal_display_formatter=None,
|
| 458 |
+
recursive=True):
|
| 459 |
+
"""
|
| 460 |
+
See :class:`FileLink` for the ``path``, ``url_prefix``,
|
| 461 |
+
``result_html_prefix`` and ``result_html_suffix`` parameters.
|
| 462 |
+
|
| 463 |
+
included_suffixes : list
|
| 464 |
+
Filename suffixes to include when formatting output [default: include
|
| 465 |
+
all files]
|
| 466 |
+
|
| 467 |
+
notebook_display_formatter : function
|
| 468 |
+
Used to format links for display in the notebook. See discussion of
|
| 469 |
+
formatter functions below.
|
| 470 |
+
|
| 471 |
+
terminal_display_formatter : function
|
| 472 |
+
Used to format links for display in the terminal. See discussion of
|
| 473 |
+
formatter functions below.
|
| 474 |
+
|
| 475 |
+
Formatter functions must be of the form::
|
| 476 |
+
|
| 477 |
+
f(dirname, fnames, included_suffixes)
|
| 478 |
+
|
| 479 |
+
dirname : str
|
| 480 |
+
The name of a directory
|
| 481 |
+
fnames : list
|
| 482 |
+
The files in that directory
|
| 483 |
+
included_suffixes : list
|
| 484 |
+
The file suffixes that should be included in the output (passing None
|
| 485 |
+
meansto include all suffixes in the output in the built-in formatters)
|
| 486 |
+
recursive : boolean
|
| 487 |
+
Whether to recurse into subdirectories. Default is True.
|
| 488 |
+
|
| 489 |
+
The function should return a list of lines that will be printed in the
|
| 490 |
+
notebook (if passing notebook_display_formatter) or the terminal (if
|
| 491 |
+
passing terminal_display_formatter). This function is iterated over for
|
| 492 |
+
each directory in self.path. Default formatters are in place, can be
|
| 493 |
+
passed here to support alternative formatting.
|
| 494 |
+
|
| 495 |
+
"""
|
| 496 |
+
if isfile(path):
|
| 497 |
+
raise ValueError("Cannot display a file using FileLinks. "
|
| 498 |
+
"Use FileLink to display '%s'." % path)
|
| 499 |
+
self.included_suffixes = included_suffixes
|
| 500 |
+
# remove trailing slashes for more consistent output formatting
|
| 501 |
+
path = path.rstrip('/')
|
| 502 |
+
|
| 503 |
+
self.path = path
|
| 504 |
+
self.url_prefix = url_prefix
|
| 505 |
+
self.result_html_prefix = result_html_prefix
|
| 506 |
+
self.result_html_suffix = result_html_suffix
|
| 507 |
+
|
| 508 |
+
self.notebook_display_formatter = \
|
| 509 |
+
notebook_display_formatter or self._get_notebook_display_formatter()
|
| 510 |
+
self.terminal_display_formatter = \
|
| 511 |
+
terminal_display_formatter or self._get_terminal_display_formatter()
|
| 512 |
+
|
| 513 |
+
self.recursive = recursive
|
| 514 |
+
|
| 515 |
+
def _get_display_formatter(
|
| 516 |
+
self, dirname_output_format, fname_output_format, fp_format, fp_cleaner=None
|
| 517 |
+
):
|
| 518 |
+
"""generate built-in formatter function
|
| 519 |
+
|
| 520 |
+
this is used to define both the notebook and terminal built-in
|
| 521 |
+
formatters as they only differ by some wrapper text for each entry
|
| 522 |
+
|
| 523 |
+
dirname_output_format: string to use for formatting directory
|
| 524 |
+
names, dirname will be substituted for a single "%s" which
|
| 525 |
+
must appear in this string
|
| 526 |
+
fname_output_format: string to use for formatting file names,
|
| 527 |
+
if a single "%s" appears in the string, fname will be substituted
|
| 528 |
+
if two "%s" appear in the string, the path to fname will be
|
| 529 |
+
substituted for the first and fname will be substituted for the
|
| 530 |
+
second
|
| 531 |
+
fp_format: string to use for formatting filepaths, must contain
|
| 532 |
+
exactly two "%s" and the dirname will be substituted for the first
|
| 533 |
+
and fname will be substituted for the second
|
| 534 |
+
"""
|
| 535 |
+
def f(dirname, fnames, included_suffixes=None):
|
| 536 |
+
result = []
|
| 537 |
+
# begin by figuring out which filenames, if any,
|
| 538 |
+
# are going to be displayed
|
| 539 |
+
display_fnames = []
|
| 540 |
+
for fname in fnames:
|
| 541 |
+
if (isfile(join(dirname,fname)) and
|
| 542 |
+
(included_suffixes is None or
|
| 543 |
+
splitext(fname)[1] in included_suffixes)):
|
| 544 |
+
display_fnames.append(fname)
|
| 545 |
+
|
| 546 |
+
if len(display_fnames) == 0:
|
| 547 |
+
# if there are no filenames to display, don't print anything
|
| 548 |
+
# (not even the directory name)
|
| 549 |
+
pass
|
| 550 |
+
else:
|
| 551 |
+
# otherwise print the formatted directory name followed by
|
| 552 |
+
# the formatted filenames
|
| 553 |
+
dirname_output_line = dirname_output_format % dirname
|
| 554 |
+
result.append(dirname_output_line)
|
| 555 |
+
for fname in display_fnames:
|
| 556 |
+
fp = fp_format % (dirname,fname)
|
| 557 |
+
if fp_cleaner is not None:
|
| 558 |
+
fp = fp_cleaner(fp)
|
| 559 |
+
try:
|
| 560 |
+
# output can include both a filepath and a filename...
|
| 561 |
+
fname_output_line = fname_output_format % (fp, fname)
|
| 562 |
+
except TypeError:
|
| 563 |
+
# ... or just a single filepath
|
| 564 |
+
fname_output_line = fname_output_format % fname
|
| 565 |
+
result.append(fname_output_line)
|
| 566 |
+
return result
|
| 567 |
+
return f
|
| 568 |
+
|
| 569 |
+
def _get_notebook_display_formatter(self,
|
| 570 |
+
spacer=" "):
|
| 571 |
+
""" generate function to use for notebook formatting
|
| 572 |
+
"""
|
| 573 |
+
dirname_output_format = \
|
| 574 |
+
self.result_html_prefix + "%s/" + self.result_html_suffix
|
| 575 |
+
fname_output_format = \
|
| 576 |
+
self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
|
| 577 |
+
fp_format = self.url_prefix + '%s/%s'
|
| 578 |
+
if sep == "\\":
|
| 579 |
+
# Working on a platform where the path separator is "\", so
|
| 580 |
+
# must convert these to "/" for generating a URI
|
| 581 |
+
def fp_cleaner(fp):
|
| 582 |
+
# Replace all occurrences of backslash ("\") with a forward
|
| 583 |
+
# slash ("/") - this is necessary on windows when a path is
|
| 584 |
+
# provided as input, but we must link to a URI
|
| 585 |
+
return fp.replace('\\','/')
|
| 586 |
+
else:
|
| 587 |
+
fp_cleaner = None
|
| 588 |
+
|
| 589 |
+
return self._get_display_formatter(dirname_output_format,
|
| 590 |
+
fname_output_format,
|
| 591 |
+
fp_format,
|
| 592 |
+
fp_cleaner)
|
| 593 |
+
|
| 594 |
+
def _get_terminal_display_formatter(self,
|
| 595 |
+
spacer=" "):
|
| 596 |
+
""" generate function to use for terminal formatting
|
| 597 |
+
"""
|
| 598 |
+
dirname_output_format = "%s/"
|
| 599 |
+
fname_output_format = spacer + "%s"
|
| 600 |
+
fp_format = '%s/%s'
|
| 601 |
+
|
| 602 |
+
return self._get_display_formatter(dirname_output_format,
|
| 603 |
+
fname_output_format,
|
| 604 |
+
fp_format)
|
| 605 |
+
|
| 606 |
+
def _format_path(self):
|
| 607 |
+
result_lines = []
|
| 608 |
+
if self.recursive:
|
| 609 |
+
walked_dir = list(walk(self.path))
|
| 610 |
+
else:
|
| 611 |
+
walked_dir = [next(walk(self.path))]
|
| 612 |
+
walked_dir.sort()
|
| 613 |
+
for dirname, subdirs, fnames in walked_dir:
|
| 614 |
+
result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
|
| 615 |
+
return '\n'.join(result_lines)
|
| 616 |
+
|
| 617 |
+
def __repr__(self):
|
| 618 |
+
"""return newline-separated absolute paths
|
| 619 |
+
"""
|
| 620 |
+
result_lines = []
|
| 621 |
+
if self.recursive:
|
| 622 |
+
walked_dir = list(walk(self.path))
|
| 623 |
+
else:
|
| 624 |
+
walked_dir = [next(walk(self.path))]
|
| 625 |
+
walked_dir.sort()
|
| 626 |
+
for dirname, subdirs, fnames in walked_dir:
|
| 627 |
+
result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
|
| 628 |
+
return '\n'.join(result_lines)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
class Code(TextDisplayObject):
|
| 632 |
+
"""Display syntax-highlighted source code.
|
| 633 |
+
|
| 634 |
+
This uses Pygments to highlight the code for HTML and Latex output.
|
| 635 |
+
|
| 636 |
+
Parameters
|
| 637 |
+
----------
|
| 638 |
+
data : str
|
| 639 |
+
The code as a string
|
| 640 |
+
url : str
|
| 641 |
+
A URL to fetch the code from
|
| 642 |
+
filename : str
|
| 643 |
+
A local filename to load the code from
|
| 644 |
+
language : str
|
| 645 |
+
The short name of a Pygments lexer to use for highlighting.
|
| 646 |
+
If not specified, it will guess the lexer based on the filename
|
| 647 |
+
or the code. Available lexers: http://pygments.org/docs/lexers/
|
| 648 |
+
"""
|
| 649 |
+
def __init__(self, data=None, url=None, filename=None, language=None):
|
| 650 |
+
self.language = language
|
| 651 |
+
super().__init__(data=data, url=url, filename=filename)
|
| 652 |
+
|
| 653 |
+
def _get_lexer(self):
|
| 654 |
+
if self.language:
|
| 655 |
+
from pygments.lexers import get_lexer_by_name
|
| 656 |
+
return get_lexer_by_name(self.language)
|
| 657 |
+
elif self.filename:
|
| 658 |
+
from pygments.lexers import get_lexer_for_filename
|
| 659 |
+
return get_lexer_for_filename(self.filename)
|
| 660 |
+
else:
|
| 661 |
+
from pygments.lexers import guess_lexer
|
| 662 |
+
return guess_lexer(self.data)
|
| 663 |
+
|
| 664 |
+
def __repr__(self):
|
| 665 |
+
return self.data
|
| 666 |
+
|
| 667 |
+
def _repr_html_(self):
|
| 668 |
+
from pygments import highlight
|
| 669 |
+
from pygments.formatters import HtmlFormatter
|
| 670 |
+
fmt = HtmlFormatter()
|
| 671 |
+
style = '<style>{}</style>'.format(fmt.get_style_defs('.output_html'))
|
| 672 |
+
return style + highlight(self.data, self._get_lexer(), fmt)
|
| 673 |
+
|
| 674 |
+
def _repr_latex_(self):
|
| 675 |
+
from pygments import highlight
|
| 676 |
+
from pygments.formatters import LatexFormatter
|
| 677 |
+
return highlight(self.data, self._get_lexer(), LatexFormatter())
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/lib/pretty.py
ADDED
|
@@ -0,0 +1,961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Python advanced pretty printer. This pretty printer is intended to
|
| 3 |
+
replace the old `pprint` python module which does not allow developers
|
| 4 |
+
to provide their own pretty print callbacks.
|
| 5 |
+
|
| 6 |
+
This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
Example Usage
|
| 10 |
+
-------------
|
| 11 |
+
|
| 12 |
+
To directly print the representation of an object use `pprint`::
|
| 13 |
+
|
| 14 |
+
from pretty import pprint
|
| 15 |
+
pprint(complex_object)
|
| 16 |
+
|
| 17 |
+
To get a string of the output use `pretty`::
|
| 18 |
+
|
| 19 |
+
from pretty import pretty
|
| 20 |
+
string = pretty(complex_object)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
Extending
|
| 24 |
+
---------
|
| 25 |
+
|
| 26 |
+
The pretty library allows developers to add pretty printing rules for their
|
| 27 |
+
own objects. This process is straightforward. All you have to do is to
|
| 28 |
+
add a `_repr_pretty_` method to your object and call the methods on the
|
| 29 |
+
pretty printer passed::
|
| 30 |
+
|
| 31 |
+
class MyObject(object):
|
| 32 |
+
|
| 33 |
+
def _repr_pretty_(self, p, cycle):
|
| 34 |
+
...
|
| 35 |
+
|
| 36 |
+
Here's an example for a class with a simple constructor::
|
| 37 |
+
|
| 38 |
+
class MySimpleObject:
|
| 39 |
+
|
| 40 |
+
def __init__(self, a, b, *, c=None):
|
| 41 |
+
self.a = a
|
| 42 |
+
self.b = b
|
| 43 |
+
self.c = c
|
| 44 |
+
|
| 45 |
+
def _repr_pretty_(self, p, cycle):
|
| 46 |
+
ctor = CallExpression.factory(self.__class__.__name__)
|
| 47 |
+
if self.c is None:
|
| 48 |
+
p.pretty(ctor(a, b))
|
| 49 |
+
else:
|
| 50 |
+
p.pretty(ctor(a, b, c=c))
|
| 51 |
+
|
| 52 |
+
Here is an example implementation of a `_repr_pretty_` method for a list
|
| 53 |
+
subclass::
|
| 54 |
+
|
| 55 |
+
class MyList(list):
|
| 56 |
+
|
| 57 |
+
def _repr_pretty_(self, p, cycle):
|
| 58 |
+
if cycle:
|
| 59 |
+
p.text('MyList(...)')
|
| 60 |
+
else:
|
| 61 |
+
with p.group(8, 'MyList([', '])'):
|
| 62 |
+
for idx, item in enumerate(self):
|
| 63 |
+
if idx:
|
| 64 |
+
p.text(',')
|
| 65 |
+
p.breakable()
|
| 66 |
+
p.pretty(item)
|
| 67 |
+
|
| 68 |
+
The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
|
| 69 |
+
react to that or the result is an infinite loop. `p.text()` just adds
|
| 70 |
+
non breaking text to the output, `p.breakable()` either adds a whitespace
|
| 71 |
+
or breaks here. If you pass it an argument it's used instead of the
|
| 72 |
+
default space. `p.pretty` prettyprints another object using the pretty print
|
| 73 |
+
method.
|
| 74 |
+
|
| 75 |
+
The first parameter to the `group` function specifies the extra indentation
|
| 76 |
+
of the next line. In this example the next item will either be on the same
|
| 77 |
+
line (if the items are short enough) or aligned with the right edge of the
|
| 78 |
+
opening bracket of `MyList`.
|
| 79 |
+
|
| 80 |
+
If you just want to indent something you can use the group function
|
| 81 |
+
without open / close parameters. You can also use this code::
|
| 82 |
+
|
| 83 |
+
with p.indent(2):
|
| 84 |
+
...
|
| 85 |
+
|
| 86 |
+
Inheritance diagram:
|
| 87 |
+
|
| 88 |
+
.. inheritance-diagram:: IPython.lib.pretty
|
| 89 |
+
:parts: 3
|
| 90 |
+
|
| 91 |
+
:copyright: 2007 by Armin Ronacher.
|
| 92 |
+
Portions (c) 2009 by Robert Kern.
|
| 93 |
+
:license: BSD License.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
from contextlib import contextmanager
|
| 97 |
+
import datetime
|
| 98 |
+
import os
|
| 99 |
+
import re
|
| 100 |
+
import sys
|
| 101 |
+
import types
|
| 102 |
+
from collections import deque
|
| 103 |
+
from inspect import signature
|
| 104 |
+
from io import StringIO
|
| 105 |
+
from warnings import warn
|
| 106 |
+
|
| 107 |
+
from IPython.utils.decorators import undoc
|
| 108 |
+
from IPython.utils.py3compat import PYPY
|
| 109 |
+
|
| 110 |
+
from typing import Dict
|
| 111 |
+
|
| 112 |
+
__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
|
| 113 |
+
'for_type', 'for_type_by_name', 'RawText', 'RawStringLiteral', 'CallExpression']
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
MAX_SEQ_LENGTH = 1000
|
| 117 |
+
_re_pattern_type = type(re.compile(''))
|
| 118 |
+
|
| 119 |
+
def _safe_getattr(obj, attr, default=None):
|
| 120 |
+
"""Safe version of getattr.
|
| 121 |
+
|
| 122 |
+
Same as getattr, but will return ``default`` on any Exception,
|
| 123 |
+
rather than raising.
|
| 124 |
+
"""
|
| 125 |
+
try:
|
| 126 |
+
return getattr(obj, attr, default)
|
| 127 |
+
except Exception:
|
| 128 |
+
return default
|
| 129 |
+
|
| 130 |
+
@undoc
|
| 131 |
+
class CUnicodeIO(StringIO):
|
| 132 |
+
def __init__(self, *args, **kwargs):
|
| 133 |
+
super().__init__(*args, **kwargs)
|
| 134 |
+
warn(("CUnicodeIO is deprecated since IPython 6.0. "
|
| 135 |
+
"Please use io.StringIO instead."),
|
| 136 |
+
DeprecationWarning, stacklevel=2)
|
| 137 |
+
|
| 138 |
+
def _sorted_for_pprint(items):
|
| 139 |
+
"""
|
| 140 |
+
Sort the given items for pretty printing. Since some predictable
|
| 141 |
+
sorting is better than no sorting at all, we sort on the string
|
| 142 |
+
representation if normal sorting fails.
|
| 143 |
+
"""
|
| 144 |
+
items = list(items)
|
| 145 |
+
try:
|
| 146 |
+
return sorted(items)
|
| 147 |
+
except Exception:
|
| 148 |
+
try:
|
| 149 |
+
return sorted(items, key=str)
|
| 150 |
+
except Exception:
|
| 151 |
+
return items
|
| 152 |
+
|
| 153 |
+
def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
|
| 154 |
+
"""
|
| 155 |
+
Pretty print the object's representation.
|
| 156 |
+
"""
|
| 157 |
+
stream = StringIO()
|
| 158 |
+
printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
|
| 159 |
+
printer.pretty(obj)
|
| 160 |
+
printer.flush()
|
| 161 |
+
return stream.getvalue()
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
|
| 165 |
+
"""
|
| 166 |
+
Like `pretty` but print to stdout.
|
| 167 |
+
"""
|
| 168 |
+
printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
|
| 169 |
+
printer.pretty(obj)
|
| 170 |
+
printer.flush()
|
| 171 |
+
sys.stdout.write(newline)
|
| 172 |
+
sys.stdout.flush()
|
| 173 |
+
|
| 174 |
+
class _PrettyPrinterBase(object):
|
| 175 |
+
|
| 176 |
+
@contextmanager
|
| 177 |
+
def indent(self, indent):
|
| 178 |
+
"""with statement support for indenting/dedenting."""
|
| 179 |
+
self.indentation += indent
|
| 180 |
+
try:
|
| 181 |
+
yield
|
| 182 |
+
finally:
|
| 183 |
+
self.indentation -= indent
|
| 184 |
+
|
| 185 |
+
@contextmanager
|
| 186 |
+
def group(self, indent=0, open='', close=''):
|
| 187 |
+
"""like begin_group / end_group but for the with statement."""
|
| 188 |
+
self.begin_group(indent, open)
|
| 189 |
+
try:
|
| 190 |
+
yield
|
| 191 |
+
finally:
|
| 192 |
+
self.end_group(indent, close)
|
| 193 |
+
|
| 194 |
+
class PrettyPrinter(_PrettyPrinterBase):
|
| 195 |
+
"""
|
| 196 |
+
Baseclass for the `RepresentationPrinter` prettyprinter that is used to
|
| 197 |
+
generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
|
| 198 |
+
this printer knows nothing about the default pprinters or the `_repr_pretty_`
|
| 199 |
+
callback method.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
|
| 203 |
+
self.output = output
|
| 204 |
+
self.max_width = max_width
|
| 205 |
+
self.newline = newline
|
| 206 |
+
self.max_seq_length = max_seq_length
|
| 207 |
+
self.output_width = 0
|
| 208 |
+
self.buffer_width = 0
|
| 209 |
+
self.buffer = deque()
|
| 210 |
+
|
| 211 |
+
root_group = Group(0)
|
| 212 |
+
self.group_stack = [root_group]
|
| 213 |
+
self.group_queue = GroupQueue(root_group)
|
| 214 |
+
self.indentation = 0
|
| 215 |
+
|
| 216 |
+
def _break_one_group(self, group):
|
| 217 |
+
while group.breakables:
|
| 218 |
+
x = self.buffer.popleft()
|
| 219 |
+
self.output_width = x.output(self.output, self.output_width)
|
| 220 |
+
self.buffer_width -= x.width
|
| 221 |
+
while self.buffer and isinstance(self.buffer[0], Text):
|
| 222 |
+
x = self.buffer.popleft()
|
| 223 |
+
self.output_width = x.output(self.output, self.output_width)
|
| 224 |
+
self.buffer_width -= x.width
|
| 225 |
+
|
| 226 |
+
def _break_outer_groups(self):
|
| 227 |
+
while self.max_width < self.output_width + self.buffer_width:
|
| 228 |
+
group = self.group_queue.deq()
|
| 229 |
+
if not group:
|
| 230 |
+
return
|
| 231 |
+
self._break_one_group(group)
|
| 232 |
+
|
| 233 |
+
def text(self, obj):
|
| 234 |
+
"""Add literal text to the output."""
|
| 235 |
+
width = len(obj)
|
| 236 |
+
if self.buffer:
|
| 237 |
+
text = self.buffer[-1]
|
| 238 |
+
if not isinstance(text, Text):
|
| 239 |
+
text = Text()
|
| 240 |
+
self.buffer.append(text)
|
| 241 |
+
text.add(obj, width)
|
| 242 |
+
self.buffer_width += width
|
| 243 |
+
self._break_outer_groups()
|
| 244 |
+
else:
|
| 245 |
+
self.output.write(obj)
|
| 246 |
+
self.output_width += width
|
| 247 |
+
|
| 248 |
+
def breakable(self, sep=' '):
|
| 249 |
+
"""
|
| 250 |
+
Add a breakable separator to the output. This does not mean that it
|
| 251 |
+
will automatically break here. If no breaking on this position takes
|
| 252 |
+
place the `sep` is inserted which default to one space.
|
| 253 |
+
"""
|
| 254 |
+
width = len(sep)
|
| 255 |
+
group = self.group_stack[-1]
|
| 256 |
+
if group.want_break:
|
| 257 |
+
self.flush()
|
| 258 |
+
self.output.write(self.newline)
|
| 259 |
+
self.output.write(' ' * self.indentation)
|
| 260 |
+
self.output_width = self.indentation
|
| 261 |
+
self.buffer_width = 0
|
| 262 |
+
else:
|
| 263 |
+
self.buffer.append(Breakable(sep, width, self))
|
| 264 |
+
self.buffer_width += width
|
| 265 |
+
self._break_outer_groups()
|
| 266 |
+
|
| 267 |
+
def break_(self):
|
| 268 |
+
"""
|
| 269 |
+
Explicitly insert a newline into the output, maintaining correct indentation.
|
| 270 |
+
"""
|
| 271 |
+
group = self.group_queue.deq()
|
| 272 |
+
if group:
|
| 273 |
+
self._break_one_group(group)
|
| 274 |
+
self.flush()
|
| 275 |
+
self.output.write(self.newline)
|
| 276 |
+
self.output.write(' ' * self.indentation)
|
| 277 |
+
self.output_width = self.indentation
|
| 278 |
+
self.buffer_width = 0
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def begin_group(self, indent=0, open=''):
|
| 282 |
+
"""
|
| 283 |
+
Begin a group.
|
| 284 |
+
The first parameter specifies the indentation for the next line (usually
|
| 285 |
+
the width of the opening text), the second the opening text. All
|
| 286 |
+
parameters are optional.
|
| 287 |
+
"""
|
| 288 |
+
if open:
|
| 289 |
+
self.text(open)
|
| 290 |
+
group = Group(self.group_stack[-1].depth + 1)
|
| 291 |
+
self.group_stack.append(group)
|
| 292 |
+
self.group_queue.enq(group)
|
| 293 |
+
self.indentation += indent
|
| 294 |
+
|
| 295 |
+
def _enumerate(self, seq):
|
| 296 |
+
"""like enumerate, but with an upper limit on the number of items"""
|
| 297 |
+
for idx, x in enumerate(seq):
|
| 298 |
+
if self.max_seq_length and idx >= self.max_seq_length:
|
| 299 |
+
self.text(',')
|
| 300 |
+
self.breakable()
|
| 301 |
+
self.text('...')
|
| 302 |
+
return
|
| 303 |
+
yield idx, x
|
| 304 |
+
|
| 305 |
+
def end_group(self, dedent=0, close=''):
|
| 306 |
+
"""End a group. See `begin_group` for more details."""
|
| 307 |
+
self.indentation -= dedent
|
| 308 |
+
group = self.group_stack.pop()
|
| 309 |
+
if not group.breakables:
|
| 310 |
+
self.group_queue.remove(group)
|
| 311 |
+
if close:
|
| 312 |
+
self.text(close)
|
| 313 |
+
|
| 314 |
+
def flush(self):
|
| 315 |
+
"""Flush data that is left in the buffer."""
|
| 316 |
+
for data in self.buffer:
|
| 317 |
+
self.output_width += data.output(self.output, self.output_width)
|
| 318 |
+
self.buffer.clear()
|
| 319 |
+
self.buffer_width = 0
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _get_mro(obj_class):
|
| 323 |
+
""" Get a reasonable method resolution order of a class and its superclasses
|
| 324 |
+
for both old-style and new-style classes.
|
| 325 |
+
"""
|
| 326 |
+
if not hasattr(obj_class, '__mro__'):
|
| 327 |
+
# Old-style class. Mix in object to make a fake new-style class.
|
| 328 |
+
try:
|
| 329 |
+
obj_class = type(obj_class.__name__, (obj_class, object), {})
|
| 330 |
+
except TypeError:
|
| 331 |
+
# Old-style extension type that does not descend from object.
|
| 332 |
+
# FIXME: try to construct a more thorough MRO.
|
| 333 |
+
mro = [obj_class]
|
| 334 |
+
else:
|
| 335 |
+
mro = obj_class.__mro__[1:-1]
|
| 336 |
+
else:
|
| 337 |
+
mro = obj_class.__mro__
|
| 338 |
+
return mro
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class RepresentationPrinter(PrettyPrinter):
|
| 342 |
+
"""
|
| 343 |
+
Special pretty printer that has a `pretty` method that calls the pretty
|
| 344 |
+
printer for a python object.
|
| 345 |
+
|
| 346 |
+
This class stores processing data on `self` so you must *never* use
|
| 347 |
+
this class in a threaded environment. Always lock it or reinstanciate
|
| 348 |
+
it.
|
| 349 |
+
|
| 350 |
+
Instances also have a verbose flag callbacks can access to control their
|
| 351 |
+
output. For example the default instance repr prints all attributes and
|
| 352 |
+
methods that are not prefixed by an underscore if the printer is in
|
| 353 |
+
verbose mode.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
def __init__(self, output, verbose=False, max_width=79, newline='\n',
|
| 357 |
+
singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
|
| 358 |
+
max_seq_length=MAX_SEQ_LENGTH):
|
| 359 |
+
|
| 360 |
+
PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
|
| 361 |
+
self.verbose = verbose
|
| 362 |
+
self.stack = []
|
| 363 |
+
if singleton_pprinters is None:
|
| 364 |
+
singleton_pprinters = _singleton_pprinters.copy()
|
| 365 |
+
self.singleton_pprinters = singleton_pprinters
|
| 366 |
+
if type_pprinters is None:
|
| 367 |
+
type_pprinters = _type_pprinters.copy()
|
| 368 |
+
self.type_pprinters = type_pprinters
|
| 369 |
+
if deferred_pprinters is None:
|
| 370 |
+
deferred_pprinters = _deferred_type_pprinters.copy()
|
| 371 |
+
self.deferred_pprinters = deferred_pprinters
|
| 372 |
+
|
| 373 |
+
def pretty(self, obj):
|
| 374 |
+
"""Pretty print the given object."""
|
| 375 |
+
obj_id = id(obj)
|
| 376 |
+
cycle = obj_id in self.stack
|
| 377 |
+
self.stack.append(obj_id)
|
| 378 |
+
self.begin_group()
|
| 379 |
+
try:
|
| 380 |
+
obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
|
| 381 |
+
# First try to find registered singleton printers for the type.
|
| 382 |
+
try:
|
| 383 |
+
printer = self.singleton_pprinters[obj_id]
|
| 384 |
+
except (TypeError, KeyError):
|
| 385 |
+
pass
|
| 386 |
+
else:
|
| 387 |
+
return printer(obj, self, cycle)
|
| 388 |
+
# Next walk the mro and check for either:
|
| 389 |
+
# 1) a registered printer
|
| 390 |
+
# 2) a _repr_pretty_ method
|
| 391 |
+
for cls in _get_mro(obj_class):
|
| 392 |
+
if cls in self.type_pprinters:
|
| 393 |
+
# printer registered in self.type_pprinters
|
| 394 |
+
return self.type_pprinters[cls](obj, self, cycle)
|
| 395 |
+
else:
|
| 396 |
+
# deferred printer
|
| 397 |
+
printer = self._in_deferred_types(cls)
|
| 398 |
+
if printer is not None:
|
| 399 |
+
return printer(obj, self, cycle)
|
| 400 |
+
else:
|
| 401 |
+
# Finally look for special method names.
|
| 402 |
+
# Some objects automatically create any requested
|
| 403 |
+
# attribute. Try to ignore most of them by checking for
|
| 404 |
+
# callability.
|
| 405 |
+
if '_repr_pretty_' in cls.__dict__:
|
| 406 |
+
meth = cls._repr_pretty_
|
| 407 |
+
if callable(meth):
|
| 408 |
+
return meth(obj, self, cycle)
|
| 409 |
+
if (
|
| 410 |
+
cls is not object
|
| 411 |
+
# check if cls defines __repr__
|
| 412 |
+
and "__repr__" in cls.__dict__
|
| 413 |
+
# check if __repr__ is callable.
|
| 414 |
+
# Note: we need to test getattr(cls, '__repr__')
|
| 415 |
+
# instead of cls.__dict__['__repr__']
|
| 416 |
+
# in order to work with descriptors like partialmethod,
|
| 417 |
+
and callable(_safe_getattr(cls, "__repr__", None))
|
| 418 |
+
):
|
| 419 |
+
return _repr_pprint(obj, self, cycle)
|
| 420 |
+
|
| 421 |
+
return _default_pprint(obj, self, cycle)
|
| 422 |
+
finally:
|
| 423 |
+
self.end_group()
|
| 424 |
+
self.stack.pop()
|
| 425 |
+
|
| 426 |
+
def _in_deferred_types(self, cls):
|
| 427 |
+
"""
|
| 428 |
+
Check if the given class is specified in the deferred type registry.
|
| 429 |
+
|
| 430 |
+
Returns the printer from the registry if it exists, and None if the
|
| 431 |
+
class is not in the registry. Successful matches will be moved to the
|
| 432 |
+
regular type registry for future use.
|
| 433 |
+
"""
|
| 434 |
+
mod = _safe_getattr(cls, '__module__', None)
|
| 435 |
+
name = _safe_getattr(cls, '__name__', None)
|
| 436 |
+
key = (mod, name)
|
| 437 |
+
printer = None
|
| 438 |
+
if key in self.deferred_pprinters:
|
| 439 |
+
# Move the printer over to the regular registry.
|
| 440 |
+
printer = self.deferred_pprinters.pop(key)
|
| 441 |
+
self.type_pprinters[cls] = printer
|
| 442 |
+
return printer
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class Printable(object):
|
| 446 |
+
|
| 447 |
+
def output(self, stream, output_width):
|
| 448 |
+
return output_width
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class Text(Printable):
|
| 452 |
+
|
| 453 |
+
def __init__(self):
|
| 454 |
+
self.objs = []
|
| 455 |
+
self.width = 0
|
| 456 |
+
|
| 457 |
+
def output(self, stream, output_width):
|
| 458 |
+
for obj in self.objs:
|
| 459 |
+
stream.write(obj)
|
| 460 |
+
return output_width + self.width
|
| 461 |
+
|
| 462 |
+
def add(self, obj, width):
|
| 463 |
+
self.objs.append(obj)
|
| 464 |
+
self.width += width
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class Breakable(Printable):
|
| 468 |
+
|
| 469 |
+
def __init__(self, seq, width, pretty):
|
| 470 |
+
self.obj = seq
|
| 471 |
+
self.width = width
|
| 472 |
+
self.pretty = pretty
|
| 473 |
+
self.indentation = pretty.indentation
|
| 474 |
+
self.group = pretty.group_stack[-1]
|
| 475 |
+
self.group.breakables.append(self)
|
| 476 |
+
|
| 477 |
+
def output(self, stream, output_width):
|
| 478 |
+
self.group.breakables.popleft()
|
| 479 |
+
if self.group.want_break:
|
| 480 |
+
stream.write(self.pretty.newline)
|
| 481 |
+
stream.write(' ' * self.indentation)
|
| 482 |
+
return self.indentation
|
| 483 |
+
if not self.group.breakables:
|
| 484 |
+
self.pretty.group_queue.remove(self.group)
|
| 485 |
+
stream.write(self.obj)
|
| 486 |
+
return output_width + self.width
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
class Group(Printable):
|
| 490 |
+
|
| 491 |
+
def __init__(self, depth):
|
| 492 |
+
self.depth = depth
|
| 493 |
+
self.breakables = deque()
|
| 494 |
+
self.want_break = False
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
class GroupQueue(object):
|
| 498 |
+
|
| 499 |
+
def __init__(self, *groups):
|
| 500 |
+
self.queue = []
|
| 501 |
+
for group in groups:
|
| 502 |
+
self.enq(group)
|
| 503 |
+
|
| 504 |
+
def enq(self, group):
|
| 505 |
+
depth = group.depth
|
| 506 |
+
while depth > len(self.queue) - 1:
|
| 507 |
+
self.queue.append([])
|
| 508 |
+
self.queue[depth].append(group)
|
| 509 |
+
|
| 510 |
+
def deq(self):
|
| 511 |
+
for stack in self.queue:
|
| 512 |
+
for idx, group in enumerate(reversed(stack)):
|
| 513 |
+
if group.breakables:
|
| 514 |
+
del stack[idx]
|
| 515 |
+
group.want_break = True
|
| 516 |
+
return group
|
| 517 |
+
for group in stack:
|
| 518 |
+
group.want_break = True
|
| 519 |
+
del stack[:]
|
| 520 |
+
|
| 521 |
+
def remove(self, group):
|
| 522 |
+
try:
|
| 523 |
+
self.queue[group.depth].remove(group)
|
| 524 |
+
except ValueError:
|
| 525 |
+
pass
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
class RawText:
|
| 529 |
+
""" Object such that ``p.pretty(RawText(value))`` is the same as ``p.text(value)``.
|
| 530 |
+
|
| 531 |
+
An example usage of this would be to show a list as binary numbers, using
|
| 532 |
+
``p.pretty([RawText(bin(i)) for i in integers])``.
|
| 533 |
+
"""
|
| 534 |
+
def __init__(self, value):
|
| 535 |
+
self.value = value
|
| 536 |
+
|
| 537 |
+
def _repr_pretty_(self, p, cycle):
|
| 538 |
+
p.text(self.value)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class CallExpression:
|
| 542 |
+
""" Object which emits a line-wrapped call expression in the form `__name(*args, **kwargs)` """
|
| 543 |
+
def __init__(__self, __name, *args, **kwargs):
|
| 544 |
+
# dunders are to avoid clashes with kwargs, as python's name managing
|
| 545 |
+
# will kick in.
|
| 546 |
+
self = __self
|
| 547 |
+
self.name = __name
|
| 548 |
+
self.args = args
|
| 549 |
+
self.kwargs = kwargs
|
| 550 |
+
|
| 551 |
+
@classmethod
|
| 552 |
+
def factory(cls, name):
|
| 553 |
+
def inner(*args, **kwargs):
|
| 554 |
+
return cls(name, *args, **kwargs)
|
| 555 |
+
return inner
|
| 556 |
+
|
| 557 |
+
def _repr_pretty_(self, p, cycle):
|
| 558 |
+
# dunders are to avoid clashes with kwargs, as python's name managing
|
| 559 |
+
# will kick in.
|
| 560 |
+
|
| 561 |
+
started = False
|
| 562 |
+
def new_item():
|
| 563 |
+
nonlocal started
|
| 564 |
+
if started:
|
| 565 |
+
p.text(",")
|
| 566 |
+
p.breakable()
|
| 567 |
+
started = True
|
| 568 |
+
|
| 569 |
+
prefix = self.name + "("
|
| 570 |
+
with p.group(len(prefix), prefix, ")"):
|
| 571 |
+
for arg in self.args:
|
| 572 |
+
new_item()
|
| 573 |
+
p.pretty(arg)
|
| 574 |
+
for arg_name, arg in self.kwargs.items():
|
| 575 |
+
new_item()
|
| 576 |
+
arg_prefix = arg_name + "="
|
| 577 |
+
with p.group(len(arg_prefix), arg_prefix):
|
| 578 |
+
p.pretty(arg)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
class RawStringLiteral:
|
| 582 |
+
""" Wrapper that shows a string with a `r` prefix """
|
| 583 |
+
def __init__(self, value):
|
| 584 |
+
self.value = value
|
| 585 |
+
|
| 586 |
+
def _repr_pretty_(self, p, cycle):
|
| 587 |
+
base_repr = repr(self.value)
|
| 588 |
+
if base_repr[:1] in 'uU':
|
| 589 |
+
base_repr = base_repr[1:]
|
| 590 |
+
prefix = 'ur'
|
| 591 |
+
else:
|
| 592 |
+
prefix = 'r'
|
| 593 |
+
base_repr = prefix + base_repr.replace('\\\\', '\\')
|
| 594 |
+
p.text(base_repr)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def _default_pprint(obj, p, cycle):
|
| 598 |
+
"""
|
| 599 |
+
The default print function. Used if an object does not provide one and
|
| 600 |
+
it's none of the builtin objects.
|
| 601 |
+
"""
|
| 602 |
+
klass = _safe_getattr(obj, '__class__', None) or type(obj)
|
| 603 |
+
if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
|
| 604 |
+
# A user-provided repr. Find newlines and replace them with p.break_()
|
| 605 |
+
_repr_pprint(obj, p, cycle)
|
| 606 |
+
return
|
| 607 |
+
p.begin_group(1, '<')
|
| 608 |
+
p.pretty(klass)
|
| 609 |
+
p.text(' at 0x%x' % id(obj))
|
| 610 |
+
if cycle:
|
| 611 |
+
p.text(' ...')
|
| 612 |
+
elif p.verbose:
|
| 613 |
+
first = True
|
| 614 |
+
for key in dir(obj):
|
| 615 |
+
if not key.startswith('_'):
|
| 616 |
+
try:
|
| 617 |
+
value = getattr(obj, key)
|
| 618 |
+
except AttributeError:
|
| 619 |
+
continue
|
| 620 |
+
if isinstance(value, types.MethodType):
|
| 621 |
+
continue
|
| 622 |
+
if not first:
|
| 623 |
+
p.text(',')
|
| 624 |
+
p.breakable()
|
| 625 |
+
p.text(key)
|
| 626 |
+
p.text('=')
|
| 627 |
+
step = len(key) + 1
|
| 628 |
+
p.indentation += step
|
| 629 |
+
p.pretty(value)
|
| 630 |
+
p.indentation -= step
|
| 631 |
+
first = False
|
| 632 |
+
p.end_group(1, '>')
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def _seq_pprinter_factory(start, end):
|
| 636 |
+
"""
|
| 637 |
+
Factory that returns a pprint function useful for sequences. Used by
|
| 638 |
+
the default pprint for tuples and lists.
|
| 639 |
+
"""
|
| 640 |
+
def inner(obj, p, cycle):
|
| 641 |
+
if cycle:
|
| 642 |
+
return p.text(start + '...' + end)
|
| 643 |
+
step = len(start)
|
| 644 |
+
p.begin_group(step, start)
|
| 645 |
+
for idx, x in p._enumerate(obj):
|
| 646 |
+
if idx:
|
| 647 |
+
p.text(',')
|
| 648 |
+
p.breakable()
|
| 649 |
+
p.pretty(x)
|
| 650 |
+
if len(obj) == 1 and isinstance(obj, tuple):
|
| 651 |
+
# Special case for 1-item tuples.
|
| 652 |
+
p.text(',')
|
| 653 |
+
p.end_group(step, end)
|
| 654 |
+
return inner
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
def _set_pprinter_factory(start, end):
|
| 658 |
+
"""
|
| 659 |
+
Factory that returns a pprint function useful for sets and frozensets.
|
| 660 |
+
"""
|
| 661 |
+
def inner(obj, p, cycle):
|
| 662 |
+
if cycle:
|
| 663 |
+
return p.text(start + '...' + end)
|
| 664 |
+
if len(obj) == 0:
|
| 665 |
+
# Special case.
|
| 666 |
+
p.text(type(obj).__name__ + '()')
|
| 667 |
+
else:
|
| 668 |
+
step = len(start)
|
| 669 |
+
p.begin_group(step, start)
|
| 670 |
+
# Like dictionary keys, we will try to sort the items if there aren't too many
|
| 671 |
+
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
|
| 672 |
+
items = _sorted_for_pprint(obj)
|
| 673 |
+
else:
|
| 674 |
+
items = obj
|
| 675 |
+
for idx, x in p._enumerate(items):
|
| 676 |
+
if idx:
|
| 677 |
+
p.text(',')
|
| 678 |
+
p.breakable()
|
| 679 |
+
p.pretty(x)
|
| 680 |
+
p.end_group(step, end)
|
| 681 |
+
return inner
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _dict_pprinter_factory(start, end):
|
| 685 |
+
"""
|
| 686 |
+
Factory that returns a pprint function used by the default pprint of
|
| 687 |
+
dicts and dict proxies.
|
| 688 |
+
"""
|
| 689 |
+
def inner(obj, p, cycle):
|
| 690 |
+
if cycle:
|
| 691 |
+
return p.text('{...}')
|
| 692 |
+
step = len(start)
|
| 693 |
+
p.begin_group(step, start)
|
| 694 |
+
keys = obj.keys()
|
| 695 |
+
for idx, key in p._enumerate(keys):
|
| 696 |
+
if idx:
|
| 697 |
+
p.text(',')
|
| 698 |
+
p.breakable()
|
| 699 |
+
p.pretty(key)
|
| 700 |
+
p.text(': ')
|
| 701 |
+
p.pretty(obj[key])
|
| 702 |
+
p.end_group(step, end)
|
| 703 |
+
return inner
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def _super_pprint(obj, p, cycle):
|
| 707 |
+
"""The pprint for the super type."""
|
| 708 |
+
p.begin_group(8, '<super: ')
|
| 709 |
+
p.pretty(obj.__thisclass__)
|
| 710 |
+
p.text(',')
|
| 711 |
+
p.breakable()
|
| 712 |
+
if PYPY: # In PyPy, super() objects don't have __self__ attributes
|
| 713 |
+
dself = obj.__repr__.__self__
|
| 714 |
+
p.pretty(None if dself is obj else dself)
|
| 715 |
+
else:
|
| 716 |
+
p.pretty(obj.__self__)
|
| 717 |
+
p.end_group(8, '>')
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
class _ReFlags:
|
| 722 |
+
def __init__(self, value):
|
| 723 |
+
self.value = value
|
| 724 |
+
|
| 725 |
+
def _repr_pretty_(self, p, cycle):
|
| 726 |
+
done_one = False
|
| 727 |
+
for flag in (
|
| 728 |
+
"IGNORECASE",
|
| 729 |
+
"LOCALE",
|
| 730 |
+
"MULTILINE",
|
| 731 |
+
"DOTALL",
|
| 732 |
+
"UNICODE",
|
| 733 |
+
"VERBOSE",
|
| 734 |
+
"DEBUG",
|
| 735 |
+
):
|
| 736 |
+
if self.value & getattr(re, flag):
|
| 737 |
+
if done_one:
|
| 738 |
+
p.text('|')
|
| 739 |
+
p.text('re.' + flag)
|
| 740 |
+
done_one = True
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _re_pattern_pprint(obj, p, cycle):
|
| 744 |
+
"""The pprint function for regular expression patterns."""
|
| 745 |
+
re_compile = CallExpression.factory('re.compile')
|
| 746 |
+
if obj.flags:
|
| 747 |
+
p.pretty(re_compile(RawStringLiteral(obj.pattern), _ReFlags(obj.flags)))
|
| 748 |
+
else:
|
| 749 |
+
p.pretty(re_compile(RawStringLiteral(obj.pattern)))
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def _types_simplenamespace_pprint(obj, p, cycle):
|
| 753 |
+
"""The pprint function for types.SimpleNamespace."""
|
| 754 |
+
namespace = CallExpression.factory('namespace')
|
| 755 |
+
if cycle:
|
| 756 |
+
p.pretty(namespace(RawText("...")))
|
| 757 |
+
else:
|
| 758 |
+
p.pretty(namespace(**obj.__dict__))
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
def _type_pprint(obj, p, cycle):
|
| 762 |
+
"""The pprint for classes and types."""
|
| 763 |
+
# Heap allocated types might not have the module attribute,
|
| 764 |
+
# and others may set it to None.
|
| 765 |
+
|
| 766 |
+
# Checks for a __repr__ override in the metaclass. Can't compare the
|
| 767 |
+
# type(obj).__repr__ directly because in PyPy the representation function
|
| 768 |
+
# inherited from type isn't the same type.__repr__
|
| 769 |
+
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
|
| 770 |
+
_repr_pprint(obj, p, cycle)
|
| 771 |
+
return
|
| 772 |
+
|
| 773 |
+
mod = _safe_getattr(obj, '__module__', None)
|
| 774 |
+
try:
|
| 775 |
+
name = obj.__qualname__
|
| 776 |
+
if not isinstance(name, str):
|
| 777 |
+
# This can happen if the type implements __qualname__ as a property
|
| 778 |
+
# or other descriptor in Python 2.
|
| 779 |
+
raise Exception("Try __name__")
|
| 780 |
+
except Exception:
|
| 781 |
+
name = obj.__name__
|
| 782 |
+
if not isinstance(name, str):
|
| 783 |
+
name = '<unknown type>'
|
| 784 |
+
|
| 785 |
+
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
|
| 786 |
+
p.text(name)
|
| 787 |
+
else:
|
| 788 |
+
p.text(mod + '.' + name)
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
def _repr_pprint(obj, p, cycle):
|
| 792 |
+
"""A pprint that just redirects to the normal repr function."""
|
| 793 |
+
# Find newlines and replace them with p.break_()
|
| 794 |
+
output = repr(obj)
|
| 795 |
+
lines = output.splitlines()
|
| 796 |
+
with p.group():
|
| 797 |
+
for idx, output_line in enumerate(lines):
|
| 798 |
+
if idx:
|
| 799 |
+
p.break_()
|
| 800 |
+
p.text(output_line)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def _function_pprint(obj, p, cycle):
|
| 804 |
+
"""Base pprint for all functions and builtin functions."""
|
| 805 |
+
name = _safe_getattr(obj, '__qualname__', obj.__name__)
|
| 806 |
+
mod = obj.__module__
|
| 807 |
+
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
|
| 808 |
+
name = mod + '.' + name
|
| 809 |
+
try:
|
| 810 |
+
func_def = name + str(signature(obj))
|
| 811 |
+
except ValueError:
|
| 812 |
+
func_def = name
|
| 813 |
+
p.text('<function %s>' % func_def)
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
def _exception_pprint(obj, p, cycle):
|
| 817 |
+
"""Base pprint for all exceptions."""
|
| 818 |
+
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
|
| 819 |
+
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
|
| 820 |
+
name = '%s.%s' % (obj.__class__.__module__, name)
|
| 821 |
+
|
| 822 |
+
p.pretty(CallExpression(name, *getattr(obj, 'args', ())))
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
#: the exception base
|
| 826 |
+
_exception_base: type
|
| 827 |
+
try:
|
| 828 |
+
_exception_base = BaseException
|
| 829 |
+
except NameError:
|
| 830 |
+
_exception_base = Exception
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
#: printers for builtin types
|
| 834 |
+
_type_pprinters = {
|
| 835 |
+
int: _repr_pprint,
|
| 836 |
+
float: _repr_pprint,
|
| 837 |
+
str: _repr_pprint,
|
| 838 |
+
tuple: _seq_pprinter_factory('(', ')'),
|
| 839 |
+
list: _seq_pprinter_factory('[', ']'),
|
| 840 |
+
dict: _dict_pprinter_factory('{', '}'),
|
| 841 |
+
set: _set_pprinter_factory('{', '}'),
|
| 842 |
+
frozenset: _set_pprinter_factory('frozenset({', '})'),
|
| 843 |
+
super: _super_pprint,
|
| 844 |
+
_re_pattern_type: _re_pattern_pprint,
|
| 845 |
+
type: _type_pprint,
|
| 846 |
+
types.FunctionType: _function_pprint,
|
| 847 |
+
types.BuiltinFunctionType: _function_pprint,
|
| 848 |
+
types.MethodType: _repr_pprint,
|
| 849 |
+
types.SimpleNamespace: _types_simplenamespace_pprint,
|
| 850 |
+
datetime.datetime: _repr_pprint,
|
| 851 |
+
datetime.timedelta: _repr_pprint,
|
| 852 |
+
_exception_base: _exception_pprint
|
| 853 |
+
}
|
| 854 |
+
|
| 855 |
+
# render os.environ like a dict
|
| 856 |
+
_env_type = type(os.environ)
|
| 857 |
+
# future-proof in case os.environ becomes a plain dict?
|
| 858 |
+
if _env_type is not dict:
|
| 859 |
+
_type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
|
| 860 |
+
|
| 861 |
+
_type_pprinters[types.MappingProxyType] = _dict_pprinter_factory("mappingproxy({", "})")
|
| 862 |
+
_type_pprinters[slice] = _repr_pprint
|
| 863 |
+
|
| 864 |
+
_type_pprinters[range] = _repr_pprint
|
| 865 |
+
_type_pprinters[bytes] = _repr_pprint
|
| 866 |
+
|
| 867 |
+
#: printers for types specified by name
|
| 868 |
+
_deferred_type_pprinters: Dict = {}
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
def for_type(typ, func):
|
| 872 |
+
"""
|
| 873 |
+
Add a pretty printer for a given type.
|
| 874 |
+
"""
|
| 875 |
+
oldfunc = _type_pprinters.get(typ, None)
|
| 876 |
+
if func is not None:
|
| 877 |
+
# To support easy restoration of old pprinters, we need to ignore Nones.
|
| 878 |
+
_type_pprinters[typ] = func
|
| 879 |
+
return oldfunc
|
| 880 |
+
|
| 881 |
+
def for_type_by_name(type_module, type_name, func):
|
| 882 |
+
"""
|
| 883 |
+
Add a pretty printer for a type specified by the module and name of a type
|
| 884 |
+
rather than the type object itself.
|
| 885 |
+
"""
|
| 886 |
+
key = (type_module, type_name)
|
| 887 |
+
oldfunc = _deferred_type_pprinters.get(key, None)
|
| 888 |
+
if func is not None:
|
| 889 |
+
# To support easy restoration of old pprinters, we need to ignore Nones.
|
| 890 |
+
_deferred_type_pprinters[key] = func
|
| 891 |
+
return oldfunc
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
#: printers for the default singletons
|
| 895 |
+
_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
|
| 896 |
+
NotImplemented]), _repr_pprint)
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def _defaultdict_pprint(obj, p, cycle):
|
| 900 |
+
cls_ctor = CallExpression.factory(obj.__class__.__name__)
|
| 901 |
+
if cycle:
|
| 902 |
+
p.pretty(cls_ctor(RawText("...")))
|
| 903 |
+
else:
|
| 904 |
+
p.pretty(cls_ctor(obj.default_factory, dict(obj)))
|
| 905 |
+
|
| 906 |
+
def _ordereddict_pprint(obj, p, cycle):
|
| 907 |
+
cls_ctor = CallExpression.factory(obj.__class__.__name__)
|
| 908 |
+
if cycle:
|
| 909 |
+
p.pretty(cls_ctor(RawText("...")))
|
| 910 |
+
elif len(obj):
|
| 911 |
+
p.pretty(cls_ctor(list(obj.items())))
|
| 912 |
+
else:
|
| 913 |
+
p.pretty(cls_ctor())
|
| 914 |
+
|
| 915 |
+
def _deque_pprint(obj, p, cycle):
|
| 916 |
+
cls_ctor = CallExpression.factory(obj.__class__.__name__)
|
| 917 |
+
if cycle:
|
| 918 |
+
p.pretty(cls_ctor(RawText("...")))
|
| 919 |
+
elif obj.maxlen is not None:
|
| 920 |
+
p.pretty(cls_ctor(list(obj), maxlen=obj.maxlen))
|
| 921 |
+
else:
|
| 922 |
+
p.pretty(cls_ctor(list(obj)))
|
| 923 |
+
|
| 924 |
+
def _counter_pprint(obj, p, cycle):
|
| 925 |
+
cls_ctor = CallExpression.factory(obj.__class__.__name__)
|
| 926 |
+
if cycle:
|
| 927 |
+
p.pretty(cls_ctor(RawText("...")))
|
| 928 |
+
elif len(obj):
|
| 929 |
+
p.pretty(cls_ctor(dict(obj.most_common())))
|
| 930 |
+
else:
|
| 931 |
+
p.pretty(cls_ctor())
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
def _userlist_pprint(obj, p, cycle):
|
| 935 |
+
cls_ctor = CallExpression.factory(obj.__class__.__name__)
|
| 936 |
+
if cycle:
|
| 937 |
+
p.pretty(cls_ctor(RawText("...")))
|
| 938 |
+
else:
|
| 939 |
+
p.pretty(cls_ctor(obj.data))
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
|
| 943 |
+
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
|
| 944 |
+
for_type_by_name('collections', 'deque', _deque_pprint)
|
| 945 |
+
for_type_by_name('collections', 'Counter', _counter_pprint)
|
| 946 |
+
for_type_by_name("collections", "UserList", _userlist_pprint)
|
| 947 |
+
|
| 948 |
+
if __name__ == '__main__':
|
| 949 |
+
from random import randrange
|
| 950 |
+
class Foo(object):
|
| 951 |
+
def __init__(self):
|
| 952 |
+
self.foo = 1
|
| 953 |
+
self.bar = re.compile(r'\s+')
|
| 954 |
+
self.blub = dict.fromkeys(range(30), randrange(1, 40))
|
| 955 |
+
self.hehe = 23424.234234
|
| 956 |
+
self.list = ["blub", "blah", self]
|
| 957 |
+
|
| 958 |
+
def get_foo(self):
|
| 959 |
+
print("foo")
|
| 960 |
+
|
| 961 |
+
pprint(Foo(), verbose=True)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/__init__.py
ADDED
|
File without changes
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/console.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shim to maintain backwards compatibility with old IPython.terminal.console imports.
|
| 3 |
+
"""
|
| 4 |
+
# Copyright (c) IPython Development Team.
|
| 5 |
+
# Distributed under the terms of the Modified BSD License.
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
from warnings import warn
|
| 9 |
+
|
| 10 |
+
from IPython.utils.shimmodule import ShimModule, ShimWarning
|
| 11 |
+
|
| 12 |
+
warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. "
|
| 13 |
+
"You should import from jupyter_console instead.", ShimWarning)
|
| 14 |
+
|
| 15 |
+
# Unconditionally insert the shim into sys.modules so that further import calls
|
| 16 |
+
# trigger the custom attribute access above
|
| 17 |
+
|
| 18 |
+
sys.modules['IPython.terminal.console'] = ShimModule(
|
| 19 |
+
src='IPython.terminal.console', mirror='jupyter_console')
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/debugger.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
from IPython.core.debugger import Pdb
|
| 6 |
+
from IPython.core.completer import IPCompleter
|
| 7 |
+
from .ptutils import IPythonPTCompleter
|
| 8 |
+
from .shortcuts import create_ipython_shortcuts
|
| 9 |
+
from . import embed
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from pygments.token import Token
|
| 13 |
+
from prompt_toolkit.application import create_app_session
|
| 14 |
+
from prompt_toolkit.shortcuts.prompt import PromptSession
|
| 15 |
+
from prompt_toolkit.enums import EditingMode
|
| 16 |
+
from prompt_toolkit.formatted_text import PygmentsTokens
|
| 17 |
+
from prompt_toolkit.history import InMemoryHistory, FileHistory
|
| 18 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 19 |
+
|
| 20 |
+
from prompt_toolkit import __version__ as ptk_version
|
| 21 |
+
PTK3 = ptk_version.startswith('3.')
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# we want to avoid ptk as much as possible when using subprocesses
|
| 25 |
+
# as it uses cursor positioning requests, deletes color ....
|
| 26 |
+
_use_simple_prompt = "IPY_TEST_SIMPLE_PROMPT" in os.environ
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TerminalPdb(Pdb):
|
| 30 |
+
"""Standalone IPython debugger."""
|
| 31 |
+
|
| 32 |
+
def __init__(self, *args, pt_session_options=None, **kwargs):
|
| 33 |
+
Pdb.__init__(self, *args, **kwargs)
|
| 34 |
+
self._ptcomp = None
|
| 35 |
+
self.pt_init(pt_session_options)
|
| 36 |
+
self.thread_executor = ThreadPoolExecutor(1)
|
| 37 |
+
|
| 38 |
+
def pt_init(self, pt_session_options=None):
|
| 39 |
+
"""Initialize the prompt session and the prompt loop
|
| 40 |
+
and store them in self.pt_app and self.pt_loop.
|
| 41 |
+
|
| 42 |
+
Additional keyword arguments for the PromptSession class
|
| 43 |
+
can be specified in pt_session_options.
|
| 44 |
+
"""
|
| 45 |
+
if pt_session_options is None:
|
| 46 |
+
pt_session_options = {}
|
| 47 |
+
|
| 48 |
+
def get_prompt_tokens():
|
| 49 |
+
return [(Token.Prompt, self.prompt)]
|
| 50 |
+
|
| 51 |
+
if self._ptcomp is None:
|
| 52 |
+
compl = IPCompleter(
|
| 53 |
+
shell=self.shell, namespace={}, global_namespace={}, parent=self.shell
|
| 54 |
+
)
|
| 55 |
+
# add a completer for all the do_ methods
|
| 56 |
+
methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
|
| 57 |
+
|
| 58 |
+
def gen_comp(self, text):
|
| 59 |
+
return [m for m in methods_names if m.startswith(text)]
|
| 60 |
+
import types
|
| 61 |
+
newcomp = types.MethodType(gen_comp, compl)
|
| 62 |
+
compl.custom_matchers.insert(0, newcomp)
|
| 63 |
+
# end add completer.
|
| 64 |
+
|
| 65 |
+
self._ptcomp = IPythonPTCompleter(compl)
|
| 66 |
+
|
| 67 |
+
# setup history only when we start pdb
|
| 68 |
+
if self.shell.debugger_history is None:
|
| 69 |
+
if self.shell.debugger_history_file is not None:
|
| 70 |
+
p = Path(self.shell.debugger_history_file).expanduser()
|
| 71 |
+
if not p.exists():
|
| 72 |
+
p.touch()
|
| 73 |
+
self.debugger_history = FileHistory(os.path.expanduser(str(p)))
|
| 74 |
+
else:
|
| 75 |
+
self.debugger_history = InMemoryHistory()
|
| 76 |
+
else:
|
| 77 |
+
self.debugger_history = self.shell.debugger_history
|
| 78 |
+
|
| 79 |
+
options = dict(
|
| 80 |
+
message=(lambda: PygmentsTokens(get_prompt_tokens())),
|
| 81 |
+
editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
|
| 82 |
+
key_bindings=create_ipython_shortcuts(self.shell),
|
| 83 |
+
history=self.debugger_history,
|
| 84 |
+
completer=self._ptcomp,
|
| 85 |
+
enable_history_search=True,
|
| 86 |
+
mouse_support=self.shell.mouse_support,
|
| 87 |
+
complete_style=self.shell.pt_complete_style,
|
| 88 |
+
style=getattr(self.shell, "style", None),
|
| 89 |
+
color_depth=self.shell.color_depth,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
if not PTK3:
|
| 93 |
+
options['inputhook'] = self.shell.inputhook
|
| 94 |
+
options.update(pt_session_options)
|
| 95 |
+
if not _use_simple_prompt:
|
| 96 |
+
self.pt_loop = asyncio.new_event_loop()
|
| 97 |
+
self.pt_app = PromptSession(**options)
|
| 98 |
+
|
| 99 |
+
def _prompt(self):
|
| 100 |
+
"""
|
| 101 |
+
In case other prompt_toolkit apps have to run in parallel to this one (e.g. in madbg),
|
| 102 |
+
create_app_session must be used to prevent mixing up between them. According to the prompt_toolkit docs:
|
| 103 |
+
|
| 104 |
+
> If you need multiple applications running at the same time, you have to create a separate
|
| 105 |
+
> `AppSession` using a `with create_app_session():` block.
|
| 106 |
+
"""
|
| 107 |
+
with create_app_session():
|
| 108 |
+
return self.pt_app.prompt()
|
| 109 |
+
|
| 110 |
+
def cmdloop(self, intro=None):
|
| 111 |
+
"""Repeatedly issue a prompt, accept input, parse an initial prefix
|
| 112 |
+
off the received input, and dispatch to action methods, passing them
|
| 113 |
+
the remainder of the line as argument.
|
| 114 |
+
|
| 115 |
+
override the same methods from cmd.Cmd to provide prompt toolkit replacement.
|
| 116 |
+
"""
|
| 117 |
+
if not self.use_rawinput:
|
| 118 |
+
raise ValueError('Sorry ipdb does not support use_rawinput=False')
|
| 119 |
+
|
| 120 |
+
# In order to make sure that prompt, which uses asyncio doesn't
|
| 121 |
+
# interfere with applications in which it's used, we always run the
|
| 122 |
+
# prompt itself in a different thread (we can't start an event loop
|
| 123 |
+
# within an event loop). This new thread won't have any event loop
|
| 124 |
+
# running, and here we run our prompt-loop.
|
| 125 |
+
self.preloop()
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
if intro is not None:
|
| 129 |
+
self.intro = intro
|
| 130 |
+
if self.intro:
|
| 131 |
+
print(self.intro, file=self.stdout)
|
| 132 |
+
stop = None
|
| 133 |
+
while not stop:
|
| 134 |
+
if self.cmdqueue:
|
| 135 |
+
line = self.cmdqueue.pop(0)
|
| 136 |
+
else:
|
| 137 |
+
self._ptcomp.ipy_completer.namespace = self.curframe_locals
|
| 138 |
+
self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
|
| 139 |
+
|
| 140 |
+
# Run the prompt in a different thread.
|
| 141 |
+
if not _use_simple_prompt:
|
| 142 |
+
try:
|
| 143 |
+
line = self.thread_executor.submit(self._prompt).result()
|
| 144 |
+
except EOFError:
|
| 145 |
+
line = "EOF"
|
| 146 |
+
else:
|
| 147 |
+
line = input("ipdb> ")
|
| 148 |
+
|
| 149 |
+
line = self.precmd(line)
|
| 150 |
+
stop = self.onecmd(line)
|
| 151 |
+
stop = self.postcmd(stop, line)
|
| 152 |
+
self.postloop()
|
| 153 |
+
except Exception:
|
| 154 |
+
raise
|
| 155 |
+
|
| 156 |
+
def do_interact(self, arg):
|
| 157 |
+
ipshell = embed.InteractiveShellEmbed(
|
| 158 |
+
config=self.shell.config,
|
| 159 |
+
banner1="*interactive*",
|
| 160 |
+
exit_msg="*exiting interactive console...*",
|
| 161 |
+
)
|
| 162 |
+
global_ns = self.curframe.f_globals
|
| 163 |
+
ipshell(
|
| 164 |
+
module=sys.modules.get(global_ns["__name__"], None),
|
| 165 |
+
local_ns=self.curframe_locals,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def set_trace(frame=None):
|
| 170 |
+
"""
|
| 171 |
+
Start debugging from `frame`.
|
| 172 |
+
|
| 173 |
+
If frame is not specified, debugging starts from caller's frame.
|
| 174 |
+
"""
|
| 175 |
+
TerminalPdb().set_trace(frame or sys._getframe().f_back)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
if __name__ == '__main__':
|
| 179 |
+
import pdb
|
| 180 |
+
# IPython.core.debugger.Pdb.trace_dispatch shall not catch
|
| 181 |
+
# bdb.BdbQuit. When started through __main__ and an exception
|
| 182 |
+
# happened after hitting "c", this is needed in order to
|
| 183 |
+
# be able to quit the debugging session (see #9950).
|
| 184 |
+
old_trace_dispatch = pdb.Pdb.trace_dispatch
|
| 185 |
+
pdb.Pdb = TerminalPdb # type: ignore
|
| 186 |
+
pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore
|
| 187 |
+
pdb.main()
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/embed.py
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
An embedded IPython shell.
|
| 4 |
+
"""
|
| 5 |
+
# Copyright (c) IPython Development Team.
|
| 6 |
+
# Distributed under the terms of the Modified BSD License.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
import sys
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from IPython.core import ultratb, compilerop
|
| 13 |
+
from IPython.core import magic_arguments
|
| 14 |
+
from IPython.core.magic import Magics, magics_class, line_magic
|
| 15 |
+
from IPython.core.interactiveshell import DummyMod, InteractiveShell
|
| 16 |
+
from IPython.terminal.interactiveshell import TerminalInteractiveShell
|
| 17 |
+
from IPython.terminal.ipapp import load_default_config
|
| 18 |
+
|
| 19 |
+
from traitlets import Bool, CBool, Unicode
|
| 20 |
+
from IPython.utils.io import ask_yes_no
|
| 21 |
+
|
| 22 |
+
from typing import Set
|
| 23 |
+
|
| 24 |
+
class KillEmbedded(Exception):pass
|
| 25 |
+
|
| 26 |
+
# kept for backward compatibility as IPython 6 was released with
|
| 27 |
+
# the typo. See https://github.com/ipython/ipython/pull/10706
|
| 28 |
+
KillEmbeded = KillEmbedded
|
| 29 |
+
|
| 30 |
+
# This is an additional magic that is exposed in embedded shells.
|
| 31 |
+
@magics_class
|
| 32 |
+
class EmbeddedMagics(Magics):
|
| 33 |
+
|
| 34 |
+
@line_magic
|
| 35 |
+
@magic_arguments.magic_arguments()
|
| 36 |
+
@magic_arguments.argument('-i', '--instance', action='store_true',
|
| 37 |
+
help='Kill instance instead of call location')
|
| 38 |
+
@magic_arguments.argument('-x', '--exit', action='store_true',
|
| 39 |
+
help='Also exit the current session')
|
| 40 |
+
@magic_arguments.argument('-y', '--yes', action='store_true',
|
| 41 |
+
help='Do not ask confirmation')
|
| 42 |
+
def kill_embedded(self, parameter_s=''):
|
| 43 |
+
"""%kill_embedded : deactivate for good the current embedded IPython
|
| 44 |
+
|
| 45 |
+
This function (after asking for confirmation) sets an internal flag so
|
| 46 |
+
that an embedded IPython will never activate again for the given call
|
| 47 |
+
location. This is useful to permanently disable a shell that is being
|
| 48 |
+
called inside a loop: once you've figured out what you needed from it,
|
| 49 |
+
you may then kill it and the program will then continue to run without
|
| 50 |
+
the interactive shell interfering again.
|
| 51 |
+
|
| 52 |
+
Kill Instance Option:
|
| 53 |
+
|
| 54 |
+
If for some reasons you need to kill the location where the instance
|
| 55 |
+
is created and not called, for example if you create a single
|
| 56 |
+
instance in one place and debug in many locations, you can use the
|
| 57 |
+
``--instance`` option to kill this specific instance. Like for the
|
| 58 |
+
``call location`` killing an "instance" should work even if it is
|
| 59 |
+
recreated within a loop.
|
| 60 |
+
|
| 61 |
+
.. note::
|
| 62 |
+
|
| 63 |
+
This was the default behavior before IPython 5.2
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s)
|
| 68 |
+
print(args)
|
| 69 |
+
if args.instance:
|
| 70 |
+
# let no ask
|
| 71 |
+
if not args.yes:
|
| 72 |
+
kill = ask_yes_no(
|
| 73 |
+
"Are you sure you want to kill this embedded instance? [y/N] ", 'n')
|
| 74 |
+
else:
|
| 75 |
+
kill = True
|
| 76 |
+
if kill:
|
| 77 |
+
self.shell._disable_init_location()
|
| 78 |
+
print("This embedded IPython instance will not reactivate anymore "
|
| 79 |
+
"once you exit.")
|
| 80 |
+
else:
|
| 81 |
+
if not args.yes:
|
| 82 |
+
kill = ask_yes_no(
|
| 83 |
+
"Are you sure you want to kill this embedded call_location? [y/N] ", 'n')
|
| 84 |
+
else:
|
| 85 |
+
kill = True
|
| 86 |
+
if kill:
|
| 87 |
+
self.shell.embedded_active = False
|
| 88 |
+
print("This embedded IPython call location will not reactivate anymore "
|
| 89 |
+
"once you exit.")
|
| 90 |
+
|
| 91 |
+
if args.exit:
|
| 92 |
+
# Ask-exit does not really ask, it just set internals flags to exit
|
| 93 |
+
# on next loop.
|
| 94 |
+
self.shell.ask_exit()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@line_magic
|
| 98 |
+
def exit_raise(self, parameter_s=''):
|
| 99 |
+
"""%exit_raise Make the current embedded kernel exit and raise and exception.
|
| 100 |
+
|
| 101 |
+
This function sets an internal flag so that an embedded IPython will
|
| 102 |
+
raise a `IPython.terminal.embed.KillEmbedded` Exception on exit, and then exit the current I. This is
|
| 103 |
+
useful to permanently exit a loop that create IPython embed instance.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
self.shell.should_raise = True
|
| 107 |
+
self.shell.ask_exit()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class _Sentinel:
|
| 111 |
+
def __init__(self, repr):
|
| 112 |
+
assert isinstance(repr, str)
|
| 113 |
+
self.repr = repr
|
| 114 |
+
|
| 115 |
+
def __repr__(self):
|
| 116 |
+
return repr
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class InteractiveShellEmbed(TerminalInteractiveShell):
|
| 120 |
+
|
| 121 |
+
dummy_mode = Bool(False)
|
| 122 |
+
exit_msg = Unicode('')
|
| 123 |
+
embedded = CBool(True)
|
| 124 |
+
should_raise = CBool(False)
|
| 125 |
+
# Like the base class display_banner is not configurable, but here it
|
| 126 |
+
# is True by default.
|
| 127 |
+
display_banner = CBool(True)
|
| 128 |
+
exit_msg = Unicode()
|
| 129 |
+
|
| 130 |
+
# When embedding, by default we don't change the terminal title
|
| 131 |
+
term_title = Bool(False,
|
| 132 |
+
help="Automatically set the terminal title"
|
| 133 |
+
).tag(config=True)
|
| 134 |
+
|
| 135 |
+
_inactive_locations: Set[str] = set()
|
| 136 |
+
|
| 137 |
+
def _disable_init_location(self):
|
| 138 |
+
"""Disable the current Instance creation location"""
|
| 139 |
+
InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
|
| 140 |
+
|
| 141 |
+
@property
|
| 142 |
+
def embedded_active(self):
|
| 143 |
+
return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\
|
| 144 |
+
and (self._init_location_id not in InteractiveShellEmbed._inactive_locations)
|
| 145 |
+
|
| 146 |
+
@embedded_active.setter
|
| 147 |
+
def embedded_active(self, value):
|
| 148 |
+
if value:
|
| 149 |
+
InteractiveShellEmbed._inactive_locations.discard(
|
| 150 |
+
self._call_location_id)
|
| 151 |
+
InteractiveShellEmbed._inactive_locations.discard(
|
| 152 |
+
self._init_location_id)
|
| 153 |
+
else:
|
| 154 |
+
InteractiveShellEmbed._inactive_locations.add(
|
| 155 |
+
self._call_location_id)
|
| 156 |
+
|
| 157 |
+
def __init__(self, **kw):
|
| 158 |
+
assert (
|
| 159 |
+
"user_global_ns" not in kw
|
| 160 |
+
), "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0."
|
| 161 |
+
# temporary fix for https://github.com/ipython/ipython/issues/14164
|
| 162 |
+
cls = type(self)
|
| 163 |
+
if cls._instance is None:
|
| 164 |
+
for subclass in cls._walk_mro():
|
| 165 |
+
subclass._instance = self
|
| 166 |
+
cls._instance = self
|
| 167 |
+
|
| 168 |
+
clid = kw.pop('_init_location_id', None)
|
| 169 |
+
if not clid:
|
| 170 |
+
frame = sys._getframe(1)
|
| 171 |
+
clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
|
| 172 |
+
self._init_location_id = clid
|
| 173 |
+
|
| 174 |
+
super(InteractiveShellEmbed,self).__init__(**kw)
|
| 175 |
+
|
| 176 |
+
# don't use the ipython crash handler so that user exceptions aren't
|
| 177 |
+
# trapped
|
| 178 |
+
sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
|
| 179 |
+
mode=self.xmode,
|
| 180 |
+
call_pdb=self.pdb)
|
| 181 |
+
|
| 182 |
+
def init_sys_modules(self):
|
| 183 |
+
"""
|
| 184 |
+
Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing.
|
| 185 |
+
"""
|
| 186 |
+
pass
|
| 187 |
+
|
| 188 |
+
def init_magics(self):
|
| 189 |
+
super(InteractiveShellEmbed, self).init_magics()
|
| 190 |
+
self.register_magics(EmbeddedMagics)
|
| 191 |
+
|
| 192 |
+
def __call__(
|
| 193 |
+
self,
|
| 194 |
+
header="",
|
| 195 |
+
local_ns=None,
|
| 196 |
+
module=None,
|
| 197 |
+
dummy=None,
|
| 198 |
+
stack_depth=1,
|
| 199 |
+
compile_flags=None,
|
| 200 |
+
**kw,
|
| 201 |
+
):
|
| 202 |
+
"""Activate the interactive interpreter.
|
| 203 |
+
|
| 204 |
+
__call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
|
| 205 |
+
the interpreter shell with the given local and global namespaces, and
|
| 206 |
+
optionally print a header string at startup.
|
| 207 |
+
|
| 208 |
+
The shell can be globally activated/deactivated using the
|
| 209 |
+
dummy_mode attribute. This allows you to turn off a shell used
|
| 210 |
+
for debugging globally.
|
| 211 |
+
|
| 212 |
+
However, *each* time you call the shell you can override the current
|
| 213 |
+
state of dummy_mode with the optional keyword parameter 'dummy'. For
|
| 214 |
+
example, if you set dummy mode on with IPShell.dummy_mode = True, you
|
| 215 |
+
can still have a specific call work by making it as IPShell(dummy=False).
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
# we are called, set the underlying interactiveshell not to exit.
|
| 219 |
+
self.keep_running = True
|
| 220 |
+
|
| 221 |
+
# If the user has turned it off, go away
|
| 222 |
+
clid = kw.pop('_call_location_id', None)
|
| 223 |
+
if not clid:
|
| 224 |
+
frame = sys._getframe(1)
|
| 225 |
+
clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
|
| 226 |
+
self._call_location_id = clid
|
| 227 |
+
|
| 228 |
+
if not self.embedded_active:
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
# Normal exits from interactive mode set this flag, so the shell can't
|
| 232 |
+
# re-enter (it checks this variable at the start of interactive mode).
|
| 233 |
+
self.exit_now = False
|
| 234 |
+
|
| 235 |
+
# Allow the dummy parameter to override the global __dummy_mode
|
| 236 |
+
if dummy or (dummy != 0 and self.dummy_mode):
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
# self.banner is auto computed
|
| 240 |
+
if header:
|
| 241 |
+
self.old_banner2 = self.banner2
|
| 242 |
+
self.banner2 = self.banner2 + '\n' + header + '\n'
|
| 243 |
+
else:
|
| 244 |
+
self.old_banner2 = ''
|
| 245 |
+
|
| 246 |
+
if self.display_banner:
|
| 247 |
+
self.show_banner()
|
| 248 |
+
|
| 249 |
+
# Call the embedding code with a stack depth of 1 so it can skip over
|
| 250 |
+
# our call and get the original caller's namespaces.
|
| 251 |
+
self.mainloop(
|
| 252 |
+
local_ns, module, stack_depth=stack_depth, compile_flags=compile_flags
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
self.banner2 = self.old_banner2
|
| 256 |
+
|
| 257 |
+
if self.exit_msg is not None:
|
| 258 |
+
print(self.exit_msg)
|
| 259 |
+
|
| 260 |
+
if self.should_raise:
|
| 261 |
+
raise KillEmbedded('Embedded IPython raising error, as user requested.')
|
| 262 |
+
|
| 263 |
+
def mainloop(
|
| 264 |
+
self,
|
| 265 |
+
local_ns=None,
|
| 266 |
+
module=None,
|
| 267 |
+
stack_depth=0,
|
| 268 |
+
compile_flags=None,
|
| 269 |
+
):
|
| 270 |
+
"""Embeds IPython into a running python program.
|
| 271 |
+
|
| 272 |
+
Parameters
|
| 273 |
+
----------
|
| 274 |
+
local_ns, module
|
| 275 |
+
Working local namespace (a dict) and module (a module or similar
|
| 276 |
+
object). If given as None, they are automatically taken from the scope
|
| 277 |
+
where the shell was called, so that program variables become visible.
|
| 278 |
+
stack_depth : int
|
| 279 |
+
How many levels in the stack to go to looking for namespaces (when
|
| 280 |
+
local_ns or module is None). This allows an intermediate caller to
|
| 281 |
+
make sure that this function gets the namespace from the intended
|
| 282 |
+
level in the stack. By default (0) it will get its locals and globals
|
| 283 |
+
from the immediate caller.
|
| 284 |
+
compile_flags
|
| 285 |
+
A bit field identifying the __future__ features
|
| 286 |
+
that are enabled, as passed to the builtin :func:`compile` function.
|
| 287 |
+
If given as None, they are automatically taken from the scope where
|
| 288 |
+
the shell was called.
|
| 289 |
+
|
| 290 |
+
"""
|
| 291 |
+
|
| 292 |
+
# Get locals and globals from caller
|
| 293 |
+
if ((local_ns is None or module is None or compile_flags is None)
|
| 294 |
+
and self.default_user_namespaces):
|
| 295 |
+
call_frame = sys._getframe(stack_depth).f_back
|
| 296 |
+
|
| 297 |
+
if local_ns is None:
|
| 298 |
+
local_ns = call_frame.f_locals
|
| 299 |
+
if module is None:
|
| 300 |
+
global_ns = call_frame.f_globals
|
| 301 |
+
try:
|
| 302 |
+
module = sys.modules[global_ns['__name__']]
|
| 303 |
+
except KeyError:
|
| 304 |
+
warnings.warn("Failed to get module %s" % \
|
| 305 |
+
global_ns.get('__name__', 'unknown module')
|
| 306 |
+
)
|
| 307 |
+
module = DummyMod()
|
| 308 |
+
module.__dict__ = global_ns
|
| 309 |
+
if compile_flags is None:
|
| 310 |
+
compile_flags = (call_frame.f_code.co_flags &
|
| 311 |
+
compilerop.PyCF_MASK)
|
| 312 |
+
|
| 313 |
+
# Save original namespace and module so we can restore them after
|
| 314 |
+
# embedding; otherwise the shell doesn't shut down correctly.
|
| 315 |
+
orig_user_module = self.user_module
|
| 316 |
+
orig_user_ns = self.user_ns
|
| 317 |
+
orig_compile_flags = self.compile.flags
|
| 318 |
+
|
| 319 |
+
# Update namespaces and fire up interpreter
|
| 320 |
+
|
| 321 |
+
# The global one is easy, we can just throw it in
|
| 322 |
+
if module is not None:
|
| 323 |
+
self.user_module = module
|
| 324 |
+
|
| 325 |
+
# But the user/local one is tricky: ipython needs it to store internal
|
| 326 |
+
# data, but we also need the locals. We'll throw our hidden variables
|
| 327 |
+
# like _ih and get_ipython() into the local namespace, but delete them
|
| 328 |
+
# later.
|
| 329 |
+
if local_ns is not None:
|
| 330 |
+
reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
|
| 331 |
+
self.user_ns = reentrant_local_ns
|
| 332 |
+
self.init_user_ns()
|
| 333 |
+
|
| 334 |
+
# Compiler flags
|
| 335 |
+
if compile_flags is not None:
|
| 336 |
+
self.compile.flags = compile_flags
|
| 337 |
+
|
| 338 |
+
# make sure the tab-completer has the correct frame information, so it
|
| 339 |
+
# actually completes using the frame's locals/globals
|
| 340 |
+
self.set_completer_frame()
|
| 341 |
+
|
| 342 |
+
with self.builtin_trap, self.display_trap:
|
| 343 |
+
self.interact()
|
| 344 |
+
|
| 345 |
+
# now, purge out the local namespace of IPython's hidden variables.
|
| 346 |
+
if local_ns is not None:
|
| 347 |
+
local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
# Restore original namespace so shell can shut down when we exit.
|
| 351 |
+
self.user_module = orig_user_module
|
| 352 |
+
self.user_ns = orig_user_ns
|
| 353 |
+
self.compile.flags = orig_compile_flags
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def embed(*, header="", compile_flags=None, **kwargs):
|
| 357 |
+
"""Call this to embed IPython at the current point in your program.
|
| 358 |
+
|
| 359 |
+
The first invocation of this will create a :class:`terminal.embed.InteractiveShellEmbed`
|
| 360 |
+
instance and then call it. Consecutive calls just call the already
|
| 361 |
+
created instance.
|
| 362 |
+
|
| 363 |
+
If you don't want the kernel to initialize the namespace
|
| 364 |
+
from the scope of the surrounding function,
|
| 365 |
+
and/or you want to load full IPython configuration,
|
| 366 |
+
you probably want `IPython.start_ipython()` instead.
|
| 367 |
+
|
| 368 |
+
Here is a simple example::
|
| 369 |
+
|
| 370 |
+
from IPython import embed
|
| 371 |
+
a = 10
|
| 372 |
+
b = 20
|
| 373 |
+
embed(header='First time')
|
| 374 |
+
c = 30
|
| 375 |
+
d = 40
|
| 376 |
+
embed()
|
| 377 |
+
|
| 378 |
+
Parameters
|
| 379 |
+
----------
|
| 380 |
+
|
| 381 |
+
header : str
|
| 382 |
+
Optional header string to print at startup.
|
| 383 |
+
compile_flags
|
| 384 |
+
Passed to the `compile_flags` parameter of :py:meth:`terminal.embed.InteractiveShellEmbed.mainloop()`,
|
| 385 |
+
which is called when the :class:`terminal.embed.InteractiveShellEmbed` instance is called.
|
| 386 |
+
**kwargs : various, optional
|
| 387 |
+
Any other kwargs will be passed to the :class:`terminal.embed.InteractiveShellEmbed` constructor.
|
| 388 |
+
Full customization can be done by passing a traitlets :class:`Config` in as the
|
| 389 |
+
`config` argument (see :ref:`configure_start_ipython` and :ref:`terminal_options`).
|
| 390 |
+
"""
|
| 391 |
+
config = kwargs.get('config')
|
| 392 |
+
if config is None:
|
| 393 |
+
config = load_default_config()
|
| 394 |
+
config.InteractiveShellEmbed = config.TerminalInteractiveShell
|
| 395 |
+
kwargs['config'] = config
|
| 396 |
+
using = kwargs.get('using', 'sync')
|
| 397 |
+
if using :
|
| 398 |
+
kwargs['config'].update({'TerminalInteractiveShell':{'loop_runner':using, 'colors':'NoColor', 'autoawait': using!='sync'}})
|
| 399 |
+
#save ps1/ps2 if defined
|
| 400 |
+
ps1 = None
|
| 401 |
+
ps2 = None
|
| 402 |
+
try:
|
| 403 |
+
ps1 = sys.ps1
|
| 404 |
+
ps2 = sys.ps2
|
| 405 |
+
except AttributeError:
|
| 406 |
+
pass
|
| 407 |
+
#save previous instance
|
| 408 |
+
saved_shell_instance = InteractiveShell._instance
|
| 409 |
+
if saved_shell_instance is not None:
|
| 410 |
+
cls = type(saved_shell_instance)
|
| 411 |
+
cls.clear_instance()
|
| 412 |
+
frame = sys._getframe(1)
|
| 413 |
+
shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
|
| 414 |
+
frame.f_code.co_filename, frame.f_lineno), **kwargs)
|
| 415 |
+
shell(header=header, stack_depth=2, compile_flags=compile_flags,
|
| 416 |
+
_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno))
|
| 417 |
+
InteractiveShellEmbed.clear_instance()
|
| 418 |
+
#restore previous instance
|
| 419 |
+
if saved_shell_instance is not None:
|
| 420 |
+
cls = type(saved_shell_instance)
|
| 421 |
+
cls.clear_instance()
|
| 422 |
+
for subclass in cls._walk_mro():
|
| 423 |
+
subclass._instance = saved_shell_instance
|
| 424 |
+
if ps1 is not None:
|
| 425 |
+
sys.ps1 = ps1
|
| 426 |
+
sys.ps2 = ps2
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/interactiveshell.py
ADDED
|
@@ -0,0 +1,1146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""IPython terminal interface using prompt_toolkit"""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import inspect
|
| 6 |
+
from warnings import warn
|
| 7 |
+
from typing import Union as UnionType, Optional
|
| 8 |
+
|
| 9 |
+
from IPython.core.async_helpers import get_asyncio_loop
|
| 10 |
+
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
|
| 11 |
+
from IPython.utils.py3compat import input
|
| 12 |
+
from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
|
| 13 |
+
from IPython.utils.process import abbrev_cwd
|
| 14 |
+
from traitlets import (
|
| 15 |
+
Bool,
|
| 16 |
+
Unicode,
|
| 17 |
+
Dict,
|
| 18 |
+
Integer,
|
| 19 |
+
List,
|
| 20 |
+
observe,
|
| 21 |
+
Instance,
|
| 22 |
+
Type,
|
| 23 |
+
default,
|
| 24 |
+
Enum,
|
| 25 |
+
Union,
|
| 26 |
+
Any,
|
| 27 |
+
validate,
|
| 28 |
+
Float,
|
| 29 |
+
DottedObjectName,
|
| 30 |
+
)
|
| 31 |
+
from traitlets.utils.importstring import import_item
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
|
| 35 |
+
from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
|
| 36 |
+
from prompt_toolkit.filters import HasFocus, Condition, IsDone
|
| 37 |
+
from prompt_toolkit.formatted_text import PygmentsTokens
|
| 38 |
+
from prompt_toolkit.history import History
|
| 39 |
+
from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
|
| 40 |
+
from prompt_toolkit.output import ColorDepth
|
| 41 |
+
from prompt_toolkit.patch_stdout import patch_stdout
|
| 42 |
+
from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
|
| 43 |
+
from prompt_toolkit.styles import DynamicStyle, merge_styles
|
| 44 |
+
from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
|
| 45 |
+
from prompt_toolkit import __version__ as ptk_version
|
| 46 |
+
|
| 47 |
+
from pygments.styles import get_style_by_name
|
| 48 |
+
from pygments.style import Style
|
| 49 |
+
from pygments.token import Token
|
| 50 |
+
|
| 51 |
+
from .debugger import TerminalPdb, Pdb
|
| 52 |
+
from .magics import TerminalMagics
|
| 53 |
+
from .pt_inputhooks import get_inputhook_name_and_func
|
| 54 |
+
from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
|
| 55 |
+
from .ptutils import IPythonPTCompleter, IPythonPTLexer
|
| 56 |
+
from .shortcuts import (
|
| 57 |
+
KEY_BINDINGS,
|
| 58 |
+
UNASSIGNED_ALLOWED_COMMANDS,
|
| 59 |
+
create_ipython_shortcuts,
|
| 60 |
+
create_identifier,
|
| 61 |
+
RuntimeBinding,
|
| 62 |
+
add_binding,
|
| 63 |
+
)
|
| 64 |
+
from .shortcuts.filters import KEYBINDING_FILTERS, filter_from_string
|
| 65 |
+
from .shortcuts.auto_suggest import (
|
| 66 |
+
NavigableAutoSuggestFromHistory,
|
| 67 |
+
AppendAutoSuggestionInAnyLine,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
PTK3 = ptk_version.startswith('3.')
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _NoStyle(Style):
|
| 74 |
+
pass
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
_style_overrides_light_bg = {
|
| 78 |
+
Token.Prompt: '#ansibrightblue',
|
| 79 |
+
Token.PromptNum: '#ansiblue bold',
|
| 80 |
+
Token.OutPrompt: '#ansibrightred',
|
| 81 |
+
Token.OutPromptNum: '#ansired bold',
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
_style_overrides_linux = {
|
| 85 |
+
Token.Prompt: '#ansibrightgreen',
|
| 86 |
+
Token.PromptNum: '#ansigreen bold',
|
| 87 |
+
Token.OutPrompt: '#ansibrightred',
|
| 88 |
+
Token.OutPromptNum: '#ansired bold',
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _backward_compat_continuation_prompt_tokens(method, width: int, *, lineno: int):
|
| 93 |
+
"""
|
| 94 |
+
Sagemath use custom prompt and we broke them in 8.19.
|
| 95 |
+
"""
|
| 96 |
+
sig = inspect.signature(method)
|
| 97 |
+
if "lineno" in inspect.signature(method).parameters or any(
|
| 98 |
+
[p.kind == p.VAR_KEYWORD for p in sig.parameters.values()]
|
| 99 |
+
):
|
| 100 |
+
return method(width, lineno=lineno)
|
| 101 |
+
else:
|
| 102 |
+
return method(width)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def get_default_editor():
|
| 106 |
+
try:
|
| 107 |
+
return os.environ['EDITOR']
|
| 108 |
+
except KeyError:
|
| 109 |
+
pass
|
| 110 |
+
except UnicodeError:
|
| 111 |
+
warn("$EDITOR environment variable is not pure ASCII. Using platform "
|
| 112 |
+
"default editor.")
|
| 113 |
+
|
| 114 |
+
if os.name == 'posix':
|
| 115 |
+
return 'vi' # the only one guaranteed to be there!
|
| 116 |
+
else:
|
| 117 |
+
return "notepad" # same in Windows!
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# conservatively check for tty
|
| 121 |
+
# overridden streams can result in things like:
|
| 122 |
+
# - sys.stdin = None
|
| 123 |
+
# - no isatty method
|
| 124 |
+
for _name in ('stdin', 'stdout', 'stderr'):
|
| 125 |
+
_stream = getattr(sys, _name)
|
| 126 |
+
try:
|
| 127 |
+
if not _stream or not hasattr(_stream, "isatty") or not _stream.isatty():
|
| 128 |
+
_is_tty = False
|
| 129 |
+
break
|
| 130 |
+
except ValueError:
|
| 131 |
+
# stream is closed
|
| 132 |
+
_is_tty = False
|
| 133 |
+
break
|
| 134 |
+
else:
|
| 135 |
+
_is_tty = True
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
|
| 139 |
+
|
| 140 |
+
def black_reformat_handler(text_before_cursor):
|
| 141 |
+
"""
|
| 142 |
+
We do not need to protect against error,
|
| 143 |
+
this is taken care at a higher level where any reformat error is ignored.
|
| 144 |
+
Indeed we may call reformatting on incomplete code.
|
| 145 |
+
"""
|
| 146 |
+
import black
|
| 147 |
+
|
| 148 |
+
formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
|
| 149 |
+
if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"):
|
| 150 |
+
formatted_text = formatted_text[:-1]
|
| 151 |
+
return formatted_text
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def yapf_reformat_handler(text_before_cursor):
|
| 155 |
+
from yapf.yapflib import file_resources
|
| 156 |
+
from yapf.yapflib import yapf_api
|
| 157 |
+
|
| 158 |
+
style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
|
| 159 |
+
formatted_text, was_formatted = yapf_api.FormatCode(
|
| 160 |
+
text_before_cursor, style_config=style_config
|
| 161 |
+
)
|
| 162 |
+
if was_formatted:
|
| 163 |
+
if not text_before_cursor.endswith("\n") and formatted_text.endswith("\n"):
|
| 164 |
+
formatted_text = formatted_text[:-1]
|
| 165 |
+
return formatted_text
|
| 166 |
+
else:
|
| 167 |
+
return text_before_cursor
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class PtkHistoryAdapter(History):
|
| 171 |
+
"""
|
| 172 |
+
Prompt toolkit has it's own way of handling history, Where it assumes it can
|
| 173 |
+
Push/pull from history.
|
| 174 |
+
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
def __init__(self, shell):
|
| 178 |
+
super().__init__()
|
| 179 |
+
self.shell = shell
|
| 180 |
+
self._refresh()
|
| 181 |
+
|
| 182 |
+
def append_string(self, string):
|
| 183 |
+
# we rely on sql for that.
|
| 184 |
+
self._loaded = False
|
| 185 |
+
self._refresh()
|
| 186 |
+
|
| 187 |
+
def _refresh(self):
|
| 188 |
+
if not self._loaded:
|
| 189 |
+
self._loaded_strings = list(self.load_history_strings())
|
| 190 |
+
|
| 191 |
+
def load_history_strings(self):
|
| 192 |
+
last_cell = ""
|
| 193 |
+
res = []
|
| 194 |
+
for __, ___, cell in self.shell.history_manager.get_tail(
|
| 195 |
+
self.shell.history_load_length, include_latest=True
|
| 196 |
+
):
|
| 197 |
+
# Ignore blank lines and consecutive duplicates
|
| 198 |
+
cell = cell.rstrip()
|
| 199 |
+
if cell and (cell != last_cell):
|
| 200 |
+
res.append(cell)
|
| 201 |
+
last_cell = cell
|
| 202 |
+
yield from res[::-1]
|
| 203 |
+
|
| 204 |
+
def store_string(self, string: str) -> None:
|
| 205 |
+
pass
|
| 206 |
+
|
| 207 |
+
class TerminalInteractiveShell(InteractiveShell):
|
| 208 |
+
mime_renderers = Dict().tag(config=True)
|
| 209 |
+
|
| 210 |
+
space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
|
| 211 |
+
'to reserve for the tab completion menu, '
|
| 212 |
+
'search history, ...etc, the height of '
|
| 213 |
+
'these menus will at most this value. '
|
| 214 |
+
'Increase it is you prefer long and skinny '
|
| 215 |
+
'menus, decrease for short and wide.'
|
| 216 |
+
).tag(config=True)
|
| 217 |
+
|
| 218 |
+
pt_app: UnionType[PromptSession, None] = None
|
| 219 |
+
auto_suggest: UnionType[
|
| 220 |
+
AutoSuggestFromHistory,
|
| 221 |
+
NavigableAutoSuggestFromHistory,
|
| 222 |
+
None,
|
| 223 |
+
] = None
|
| 224 |
+
debugger_history = None
|
| 225 |
+
|
| 226 |
+
debugger_history_file = Unicode(
|
| 227 |
+
"~/.pdbhistory", help="File in which to store and read history"
|
| 228 |
+
).tag(config=True)
|
| 229 |
+
|
| 230 |
+
simple_prompt = Bool(_use_simple_prompt,
|
| 231 |
+
help="""Use `raw_input` for the REPL, without completion and prompt colors.
|
| 232 |
+
|
| 233 |
+
Useful when controlling IPython as a subprocess, and piping
|
| 234 |
+
STDIN/OUT/ERR. Known usage are: IPython's own testing machinery,
|
| 235 |
+
and emacs' inferior-python subprocess (assuming you have set
|
| 236 |
+
`python-shell-interpreter` to "ipython") available through the
|
| 237 |
+
built-in `M-x run-python` and third party packages such as elpy.
|
| 238 |
+
|
| 239 |
+
This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
|
| 240 |
+
environment variable is set, or the current terminal is not a tty.
|
| 241 |
+
Thus the Default value reported in --help-all, or config will often
|
| 242 |
+
be incorrectly reported.
|
| 243 |
+
""",
|
| 244 |
+
).tag(config=True)
|
| 245 |
+
|
| 246 |
+
@property
|
| 247 |
+
def debugger_cls(self):
|
| 248 |
+
return Pdb if self.simple_prompt else TerminalPdb
|
| 249 |
+
|
| 250 |
+
confirm_exit = Bool(True,
|
| 251 |
+
help="""
|
| 252 |
+
Set to confirm when you try to exit IPython with an EOF (Control-D
|
| 253 |
+
in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
|
| 254 |
+
you can force a direct exit without any confirmation.""",
|
| 255 |
+
).tag(config=True)
|
| 256 |
+
|
| 257 |
+
editing_mode = Unicode('emacs',
|
| 258 |
+
help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
|
| 259 |
+
).tag(config=True)
|
| 260 |
+
|
| 261 |
+
emacs_bindings_in_vi_insert_mode = Bool(
|
| 262 |
+
True,
|
| 263 |
+
help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.",
|
| 264 |
+
).tag(config=True)
|
| 265 |
+
|
| 266 |
+
modal_cursor = Bool(
|
| 267 |
+
True,
|
| 268 |
+
help="""
|
| 269 |
+
Cursor shape changes depending on vi mode: beam in vi insert mode,
|
| 270 |
+
block in nav mode, underscore in replace mode.""",
|
| 271 |
+
).tag(config=True)
|
| 272 |
+
|
| 273 |
+
ttimeoutlen = Float(
|
| 274 |
+
0.01,
|
| 275 |
+
help="""The time in milliseconds that is waited for a key code
|
| 276 |
+
to complete.""",
|
| 277 |
+
).tag(config=True)
|
| 278 |
+
|
| 279 |
+
timeoutlen = Float(
|
| 280 |
+
0.5,
|
| 281 |
+
help="""The time in milliseconds that is waited for a mapped key
|
| 282 |
+
sequence to complete.""",
|
| 283 |
+
).tag(config=True)
|
| 284 |
+
|
| 285 |
+
autoformatter = Unicode(
|
| 286 |
+
None,
|
| 287 |
+
help="Autoformatter to reformat Terminal code. Can be `'black'`, `'yapf'` or `None`",
|
| 288 |
+
allow_none=True
|
| 289 |
+
).tag(config=True)
|
| 290 |
+
|
| 291 |
+
auto_match = Bool(
|
| 292 |
+
False,
|
| 293 |
+
help="""
|
| 294 |
+
Automatically add/delete closing bracket or quote when opening bracket or quote is entered/deleted.
|
| 295 |
+
Brackets: (), [], {}
|
| 296 |
+
Quotes: '', \"\"
|
| 297 |
+
""",
|
| 298 |
+
).tag(config=True)
|
| 299 |
+
|
| 300 |
+
mouse_support = Bool(False,
|
| 301 |
+
help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
|
| 302 |
+
).tag(config=True)
|
| 303 |
+
|
| 304 |
+
# We don't load the list of styles for the help string, because loading
|
| 305 |
+
# Pygments plugins takes time and can cause unexpected errors.
|
| 306 |
+
highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
|
| 307 |
+
help="""The name or class of a Pygments style to use for syntax
|
| 308 |
+
highlighting. To see available styles, run `pygmentize -L styles`."""
|
| 309 |
+
).tag(config=True)
|
| 310 |
+
|
| 311 |
+
@validate('editing_mode')
|
| 312 |
+
def _validate_editing_mode(self, proposal):
|
| 313 |
+
if proposal['value'].lower() == 'vim':
|
| 314 |
+
proposal['value']= 'vi'
|
| 315 |
+
elif proposal['value'].lower() == 'default':
|
| 316 |
+
proposal['value']= 'emacs'
|
| 317 |
+
|
| 318 |
+
if hasattr(EditingMode, proposal['value'].upper()):
|
| 319 |
+
return proposal['value'].lower()
|
| 320 |
+
|
| 321 |
+
return self.editing_mode
|
| 322 |
+
|
| 323 |
+
@observe('editing_mode')
|
| 324 |
+
def _editing_mode(self, change):
|
| 325 |
+
if self.pt_app:
|
| 326 |
+
self.pt_app.editing_mode = getattr(EditingMode, change.new.upper())
|
| 327 |
+
|
| 328 |
+
def _set_formatter(self, formatter):
|
| 329 |
+
if formatter is None:
|
| 330 |
+
self.reformat_handler = lambda x:x
|
| 331 |
+
elif formatter == 'black':
|
| 332 |
+
self.reformat_handler = black_reformat_handler
|
| 333 |
+
elif formatter == "yapf":
|
| 334 |
+
self.reformat_handler = yapf_reformat_handler
|
| 335 |
+
else:
|
| 336 |
+
raise ValueError
|
| 337 |
+
|
| 338 |
+
@observe("autoformatter")
|
| 339 |
+
def _autoformatter_changed(self, change):
|
| 340 |
+
formatter = change.new
|
| 341 |
+
self._set_formatter(formatter)
|
| 342 |
+
|
| 343 |
+
@observe('highlighting_style')
|
| 344 |
+
@observe('colors')
|
| 345 |
+
def _highlighting_style_changed(self, change):
|
| 346 |
+
self.refresh_style()
|
| 347 |
+
|
| 348 |
+
def refresh_style(self):
|
| 349 |
+
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
|
| 350 |
+
|
| 351 |
+
highlighting_style_overrides = Dict(
|
| 352 |
+
help="Override highlighting format for specific tokens"
|
| 353 |
+
).tag(config=True)
|
| 354 |
+
|
| 355 |
+
true_color = Bool(False,
|
| 356 |
+
help="""Use 24bit colors instead of 256 colors in prompt highlighting.
|
| 357 |
+
If your terminal supports true color, the following command should
|
| 358 |
+
print ``TRUECOLOR`` in orange::
|
| 359 |
+
|
| 360 |
+
printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"
|
| 361 |
+
""",
|
| 362 |
+
).tag(config=True)
|
| 363 |
+
|
| 364 |
+
editor = Unicode(get_default_editor(),
|
| 365 |
+
help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
|
| 366 |
+
).tag(config=True)
|
| 367 |
+
|
| 368 |
+
prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
|
| 369 |
+
|
| 370 |
+
prompts = Instance(Prompts)
|
| 371 |
+
|
| 372 |
+
@default('prompts')
|
| 373 |
+
def _prompts_default(self):
|
| 374 |
+
return self.prompts_class(self)
|
| 375 |
+
|
| 376 |
+
# @observe('prompts')
|
| 377 |
+
# def _(self, change):
|
| 378 |
+
# self._update_layout()
|
| 379 |
+
|
| 380 |
+
@default('displayhook_class')
|
| 381 |
+
def _displayhook_class_default(self):
|
| 382 |
+
return RichPromptDisplayHook
|
| 383 |
+
|
| 384 |
+
term_title = Bool(True,
|
| 385 |
+
help="Automatically set the terminal title"
|
| 386 |
+
).tag(config=True)
|
| 387 |
+
|
| 388 |
+
term_title_format = Unicode("IPython: {cwd}",
|
| 389 |
+
help="Customize the terminal title format. This is a python format string. " +
|
| 390 |
+
"Available substitutions are: {cwd}."
|
| 391 |
+
).tag(config=True)
|
| 392 |
+
|
| 393 |
+
display_completions = Enum(('column', 'multicolumn','readlinelike'),
|
| 394 |
+
help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
|
| 395 |
+
"'readlinelike'. These options are for `prompt_toolkit`, see "
|
| 396 |
+
"`prompt_toolkit` documentation for more information."
|
| 397 |
+
),
|
| 398 |
+
default_value='multicolumn').tag(config=True)
|
| 399 |
+
|
| 400 |
+
highlight_matching_brackets = Bool(True,
|
| 401 |
+
help="Highlight matching brackets.",
|
| 402 |
+
).tag(config=True)
|
| 403 |
+
|
| 404 |
+
extra_open_editor_shortcuts = Bool(False,
|
| 405 |
+
help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
|
| 406 |
+
"This is in addition to the F2 binding, which is always enabled."
|
| 407 |
+
).tag(config=True)
|
| 408 |
+
|
| 409 |
+
handle_return = Any(None,
|
| 410 |
+
help="Provide an alternative handler to be called when the user presses "
|
| 411 |
+
"Return. This is an advanced option intended for debugging, which "
|
| 412 |
+
"may be changed or removed in later releases."
|
| 413 |
+
).tag(config=True)
|
| 414 |
+
|
| 415 |
+
enable_history_search = Bool(True,
|
| 416 |
+
help="Allows to enable/disable the prompt toolkit history search"
|
| 417 |
+
).tag(config=True)
|
| 418 |
+
|
| 419 |
+
autosuggestions_provider = Unicode(
|
| 420 |
+
"NavigableAutoSuggestFromHistory",
|
| 421 |
+
help="Specifies from which source automatic suggestions are provided. "
|
| 422 |
+
"Can be set to ``'NavigableAutoSuggestFromHistory'`` (:kbd:`up` and "
|
| 423 |
+
":kbd:`down` swap suggestions), ``'AutoSuggestFromHistory'``, "
|
| 424 |
+
" or ``None`` to disable automatic suggestions. "
|
| 425 |
+
"Default is `'NavigableAutoSuggestFromHistory`'.",
|
| 426 |
+
allow_none=True,
|
| 427 |
+
).tag(config=True)
|
| 428 |
+
_autosuggestions_provider: Any
|
| 429 |
+
|
| 430 |
+
llm_constructor_kwargs = Dict(
|
| 431 |
+
{},
|
| 432 |
+
help="""
|
| 433 |
+
Extra arguments to pass to `llm_provider_class` constructor.
|
| 434 |
+
|
| 435 |
+
This is used to – for example – set the `model_id`""",
|
| 436 |
+
).tag(config=True)
|
| 437 |
+
|
| 438 |
+
llm_prefix_from_history = DottedObjectName(
|
| 439 |
+
"input_history",
|
| 440 |
+
help="""\
|
| 441 |
+
Fully Qualifed name of a function that takes an IPython history manager and
|
| 442 |
+
return a prefix to pass the llm provider in addition to the current buffer
|
| 443 |
+
text.
|
| 444 |
+
|
| 445 |
+
You can use:
|
| 446 |
+
|
| 447 |
+
- no_prefix
|
| 448 |
+
- input_history
|
| 449 |
+
|
| 450 |
+
As default value. `input_history` (default), will use all the input history
|
| 451 |
+
of current IPython session
|
| 452 |
+
|
| 453 |
+
""",
|
| 454 |
+
).tag(config=True)
|
| 455 |
+
_llm_prefix_from_history: Any
|
| 456 |
+
|
| 457 |
+
@observe("llm_prefix_from_history")
|
| 458 |
+
def _llm_prefix_from_history_changed(self, change):
|
| 459 |
+
name = change.new
|
| 460 |
+
self._llm_prefix_from_history = name
|
| 461 |
+
self._set_autosuggestions()
|
| 462 |
+
|
| 463 |
+
llm_provider_class = DottedObjectName(
|
| 464 |
+
None,
|
| 465 |
+
allow_none=True,
|
| 466 |
+
help="""\
|
| 467 |
+
Provisional:
|
| 468 |
+
This is a provisinal API in IPython 8.32, before stabilisation
|
| 469 |
+
in 9.0, it may change without warnings.
|
| 470 |
+
|
| 471 |
+
class to use for the `NavigableAutoSuggestFromHistory` to request
|
| 472 |
+
completions from a LLM, this should inherit from
|
| 473 |
+
`jupyter_ai_magics:BaseProvider` and implement
|
| 474 |
+
`stream_inline_completions`
|
| 475 |
+
""",
|
| 476 |
+
).tag(config=True)
|
| 477 |
+
_llm_provider_class: Any = None
|
| 478 |
+
|
| 479 |
+
@observe("llm_provider_class")
|
| 480 |
+
def _llm_provider_class_changed(self, change):
|
| 481 |
+
provider_class = change.new
|
| 482 |
+
if provider_class is not None:
|
| 483 |
+
warn(
|
| 484 |
+
"TerminalInteractiveShell.llm_provider_class is a provisional"
|
| 485 |
+
" API as of IPython 8.32, and may change without warnings."
|
| 486 |
+
)
|
| 487 |
+
self._llm_provider_class = provider_class
|
| 488 |
+
self._set_autosuggestions()
|
| 489 |
+
|
| 490 |
+
def _set_autosuggestions(self, provider=None):
|
| 491 |
+
if provider is None:
|
| 492 |
+
provider = self.autosuggestions_provider
|
| 493 |
+
# disconnect old handler
|
| 494 |
+
if self.auto_suggest and isinstance(
|
| 495 |
+
self.auto_suggest, NavigableAutoSuggestFromHistory
|
| 496 |
+
):
|
| 497 |
+
self.auto_suggest.disconnect()
|
| 498 |
+
if provider is None:
|
| 499 |
+
self.auto_suggest = None
|
| 500 |
+
elif provider == "AutoSuggestFromHistory":
|
| 501 |
+
self.auto_suggest = AutoSuggestFromHistory()
|
| 502 |
+
elif provider == "NavigableAutoSuggestFromHistory":
|
| 503 |
+
# LLM stuff are all Provisional in 8.32
|
| 504 |
+
if self._llm_provider_class:
|
| 505 |
+
llm_provider_constructor = import_item(self._llm_provider_class)
|
| 506 |
+
llm_provider = llm_provider_constructor(**self.llm_constructor_kwargs)
|
| 507 |
+
else:
|
| 508 |
+
llm_provider = None
|
| 509 |
+
self.auto_suggest = NavigableAutoSuggestFromHistory()
|
| 510 |
+
# Provisinal in 8.32
|
| 511 |
+
self.auto_suggest._llm_provider = llm_provider
|
| 512 |
+
|
| 513 |
+
name = self.llm_prefix_from_history
|
| 514 |
+
|
| 515 |
+
if name == "no_prefix":
|
| 516 |
+
|
| 517 |
+
def no_prefix(history_manager):
|
| 518 |
+
return ""
|
| 519 |
+
|
| 520 |
+
fun = no_prefix
|
| 521 |
+
|
| 522 |
+
elif name == "input_history":
|
| 523 |
+
|
| 524 |
+
def input_history(history_manager):
|
| 525 |
+
return "\n".join([s[2] for s in history_manager.get_range()]) + "\n"
|
| 526 |
+
|
| 527 |
+
fun = input_history
|
| 528 |
+
|
| 529 |
+
else:
|
| 530 |
+
fun = import_item(name)
|
| 531 |
+
self.auto_suggest._llm_prefixer = fun
|
| 532 |
+
else:
|
| 533 |
+
raise ValueError("No valid provider.")
|
| 534 |
+
if self.pt_app:
|
| 535 |
+
self.pt_app.auto_suggest = self.auto_suggest
|
| 536 |
+
|
| 537 |
+
@observe("autosuggestions_provider")
|
| 538 |
+
def _autosuggestions_provider_changed(self, change):
|
| 539 |
+
provider = change.new
|
| 540 |
+
self._set_autosuggestions(provider)
|
| 541 |
+
|
| 542 |
+
shortcuts = List(
|
| 543 |
+
trait=Dict(
|
| 544 |
+
key_trait=Enum(
|
| 545 |
+
[
|
| 546 |
+
"command",
|
| 547 |
+
"match_keys",
|
| 548 |
+
"match_filter",
|
| 549 |
+
"new_keys",
|
| 550 |
+
"new_filter",
|
| 551 |
+
"create",
|
| 552 |
+
]
|
| 553 |
+
),
|
| 554 |
+
per_key_traits={
|
| 555 |
+
"command": Unicode(),
|
| 556 |
+
"match_keys": List(Unicode()),
|
| 557 |
+
"match_filter": Unicode(),
|
| 558 |
+
"new_keys": List(Unicode()),
|
| 559 |
+
"new_filter": Unicode(),
|
| 560 |
+
"create": Bool(False),
|
| 561 |
+
},
|
| 562 |
+
),
|
| 563 |
+
help="""
|
| 564 |
+
Add, disable or modifying shortcuts.
|
| 565 |
+
|
| 566 |
+
Each entry on the list should be a dictionary with ``command`` key
|
| 567 |
+
identifying the target function executed by the shortcut and at least
|
| 568 |
+
one of the following:
|
| 569 |
+
|
| 570 |
+
- ``match_keys``: list of keys used to match an existing shortcut,
|
| 571 |
+
- ``match_filter``: shortcut filter used to match an existing shortcut,
|
| 572 |
+
- ``new_keys``: list of keys to set,
|
| 573 |
+
- ``new_filter``: a new shortcut filter to set
|
| 574 |
+
|
| 575 |
+
The filters have to be composed of pre-defined verbs and joined by one
|
| 576 |
+
of the following conjunctions: ``&`` (and), ``|`` (or), ``~`` (not).
|
| 577 |
+
The pre-defined verbs are:
|
| 578 |
+
|
| 579 |
+
{filters}
|
| 580 |
+
|
| 581 |
+
To disable a shortcut set ``new_keys`` to an empty list.
|
| 582 |
+
To add a shortcut add key ``create`` with value ``True``.
|
| 583 |
+
|
| 584 |
+
When modifying/disabling shortcuts, ``match_keys``/``match_filter`` can
|
| 585 |
+
be omitted if the provided specification uniquely identifies a shortcut
|
| 586 |
+
to be modified/disabled. When modifying a shortcut ``new_filter`` or
|
| 587 |
+
``new_keys`` can be omitted which will result in reuse of the existing
|
| 588 |
+
filter/keys.
|
| 589 |
+
|
| 590 |
+
Only shortcuts defined in IPython (and not default prompt-toolkit
|
| 591 |
+
shortcuts) can be modified or disabled. The full list of shortcuts,
|
| 592 |
+
command identifiers and filters is available under
|
| 593 |
+
:ref:`terminal-shortcuts-list`.
|
| 594 |
+
|
| 595 |
+
Here is an example:
|
| 596 |
+
|
| 597 |
+
.. code::
|
| 598 |
+
|
| 599 |
+
c.TerminalInteractiveShell.shortcuts = [
|
| 600 |
+
{{
|
| 601 |
+
"new_keys": ["c-q"],
|
| 602 |
+
"command": "prompt_toolkit:named_commands.capitalize_word",
|
| 603 |
+
"create": True,
|
| 604 |
+
}},
|
| 605 |
+
{{
|
| 606 |
+
"new_keys": ["c-j"],
|
| 607 |
+
"command": "prompt_toolkit:named_commands.beginning_of_line",
|
| 608 |
+
"create": True,
|
| 609 |
+
}},
|
| 610 |
+
]
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
""".format(
|
| 614 |
+
filters="\n ".join([f" - ``{k}``" for k in KEYBINDING_FILTERS])
|
| 615 |
+
),
|
| 616 |
+
).tag(config=True)
|
| 617 |
+
|
| 618 |
+
@observe("shortcuts")
|
| 619 |
+
def _shortcuts_changed(self, change):
|
| 620 |
+
if self.pt_app:
|
| 621 |
+
self.pt_app.key_bindings = self._merge_shortcuts(user_shortcuts=change.new)
|
| 622 |
+
|
| 623 |
+
def _merge_shortcuts(self, user_shortcuts):
|
| 624 |
+
# rebuild the bindings list from scratch
|
| 625 |
+
key_bindings = create_ipython_shortcuts(self)
|
| 626 |
+
|
| 627 |
+
# for now we only allow adding shortcuts for a specific set of
|
| 628 |
+
# commands; this is a security precution.
|
| 629 |
+
allowed_commands = {
|
| 630 |
+
create_identifier(binding.command): binding.command
|
| 631 |
+
for binding in KEY_BINDINGS
|
| 632 |
+
}
|
| 633 |
+
allowed_commands.update(
|
| 634 |
+
{
|
| 635 |
+
create_identifier(command): command
|
| 636 |
+
for command in UNASSIGNED_ALLOWED_COMMANDS
|
| 637 |
+
}
|
| 638 |
+
)
|
| 639 |
+
shortcuts_to_skip = []
|
| 640 |
+
shortcuts_to_add = []
|
| 641 |
+
|
| 642 |
+
for shortcut in user_shortcuts:
|
| 643 |
+
command_id = shortcut["command"]
|
| 644 |
+
if command_id not in allowed_commands:
|
| 645 |
+
allowed_commands = "\n - ".join(allowed_commands)
|
| 646 |
+
raise ValueError(
|
| 647 |
+
f"{command_id} is not a known shortcut command."
|
| 648 |
+
f" Allowed commands are: \n - {allowed_commands}"
|
| 649 |
+
)
|
| 650 |
+
old_keys = shortcut.get("match_keys", None)
|
| 651 |
+
old_filter = (
|
| 652 |
+
filter_from_string(shortcut["match_filter"])
|
| 653 |
+
if "match_filter" in shortcut
|
| 654 |
+
else None
|
| 655 |
+
)
|
| 656 |
+
matching = [
|
| 657 |
+
binding
|
| 658 |
+
for binding in KEY_BINDINGS
|
| 659 |
+
if (
|
| 660 |
+
(old_filter is None or binding.filter == old_filter)
|
| 661 |
+
and (old_keys is None or [k for k in binding.keys] == old_keys)
|
| 662 |
+
and create_identifier(binding.command) == command_id
|
| 663 |
+
)
|
| 664 |
+
]
|
| 665 |
+
|
| 666 |
+
new_keys = shortcut.get("new_keys", None)
|
| 667 |
+
new_filter = shortcut.get("new_filter", None)
|
| 668 |
+
|
| 669 |
+
command = allowed_commands[command_id]
|
| 670 |
+
|
| 671 |
+
creating_new = shortcut.get("create", False)
|
| 672 |
+
modifying_existing = not creating_new and (
|
| 673 |
+
new_keys is not None or new_filter
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
if creating_new and new_keys == []:
|
| 677 |
+
raise ValueError("Cannot add a shortcut without keys")
|
| 678 |
+
|
| 679 |
+
if modifying_existing:
|
| 680 |
+
specification = {
|
| 681 |
+
key: shortcut[key]
|
| 682 |
+
for key in ["command", "filter"]
|
| 683 |
+
if key in shortcut
|
| 684 |
+
}
|
| 685 |
+
if len(matching) == 0:
|
| 686 |
+
raise ValueError(
|
| 687 |
+
f"No shortcuts matching {specification} found in {KEY_BINDINGS}"
|
| 688 |
+
)
|
| 689 |
+
elif len(matching) > 1:
|
| 690 |
+
raise ValueError(
|
| 691 |
+
f"Multiple shortcuts matching {specification} found,"
|
| 692 |
+
f" please add keys/filter to select one of: {matching}"
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
matched = matching[0]
|
| 696 |
+
old_filter = matched.filter
|
| 697 |
+
old_keys = list(matched.keys)
|
| 698 |
+
shortcuts_to_skip.append(
|
| 699 |
+
RuntimeBinding(
|
| 700 |
+
command,
|
| 701 |
+
keys=old_keys,
|
| 702 |
+
filter=old_filter,
|
| 703 |
+
)
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
if new_keys != []:
|
| 707 |
+
shortcuts_to_add.append(
|
| 708 |
+
RuntimeBinding(
|
| 709 |
+
command,
|
| 710 |
+
keys=new_keys or old_keys,
|
| 711 |
+
filter=(
|
| 712 |
+
filter_from_string(new_filter)
|
| 713 |
+
if new_filter is not None
|
| 714 |
+
else (
|
| 715 |
+
old_filter
|
| 716 |
+
if old_filter is not None
|
| 717 |
+
else filter_from_string("always")
|
| 718 |
+
)
|
| 719 |
+
),
|
| 720 |
+
)
|
| 721 |
+
)
|
| 722 |
+
|
| 723 |
+
# rebuild the bindings list from scratch
|
| 724 |
+
key_bindings = create_ipython_shortcuts(self, skip=shortcuts_to_skip)
|
| 725 |
+
for binding in shortcuts_to_add:
|
| 726 |
+
add_binding(key_bindings, binding)
|
| 727 |
+
|
| 728 |
+
return key_bindings
|
| 729 |
+
|
| 730 |
+
prompt_includes_vi_mode = Bool(True,
|
| 731 |
+
help="Display the current vi mode (when using vi editing mode)."
|
| 732 |
+
).tag(config=True)
|
| 733 |
+
|
| 734 |
+
prompt_line_number_format = Unicode(
|
| 735 |
+
"",
|
| 736 |
+
help="The format for line numbering, will be passed `line` (int, 1 based)"
|
| 737 |
+
" the current line number and `rel_line` the relative line number."
|
| 738 |
+
" for example to display both you can use the following template string :"
|
| 739 |
+
" c.TerminalInteractiveShell.prompt_line_number_format='{line: 4d}/{rel_line:+03d} | '"
|
| 740 |
+
" This will display the current line number, with leading space and a width of at least 4"
|
| 741 |
+
" character, as well as the relative line number 0 padded and always with a + or - sign."
|
| 742 |
+
" Note that when using Emacs mode the prompt of the first line may not update.",
|
| 743 |
+
).tag(config=True)
|
| 744 |
+
|
| 745 |
+
@observe('term_title')
|
| 746 |
+
def init_term_title(self, change=None):
|
| 747 |
+
# Enable or disable the terminal title.
|
| 748 |
+
if self.term_title and _is_tty:
|
| 749 |
+
toggle_set_term_title(True)
|
| 750 |
+
set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
|
| 751 |
+
else:
|
| 752 |
+
toggle_set_term_title(False)
|
| 753 |
+
|
| 754 |
+
def restore_term_title(self):
|
| 755 |
+
if self.term_title and _is_tty:
|
| 756 |
+
restore_term_title()
|
| 757 |
+
|
| 758 |
+
def init_display_formatter(self):
|
| 759 |
+
super(TerminalInteractiveShell, self).init_display_formatter()
|
| 760 |
+
# terminal only supports plain text
|
| 761 |
+
self.display_formatter.active_types = ["text/plain"]
|
| 762 |
+
|
| 763 |
+
def init_prompt_toolkit_cli(self):
|
| 764 |
+
if self.simple_prompt:
|
| 765 |
+
# Fall back to plain non-interactive output for tests.
|
| 766 |
+
# This is very limited.
|
| 767 |
+
def prompt():
|
| 768 |
+
prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
|
| 769 |
+
lines = [input(prompt_text)]
|
| 770 |
+
prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
|
| 771 |
+
while self.check_complete('\n'.join(lines))[0] == 'incomplete':
|
| 772 |
+
lines.append( input(prompt_continuation) )
|
| 773 |
+
return '\n'.join(lines)
|
| 774 |
+
self.prompt_for_code = prompt
|
| 775 |
+
return
|
| 776 |
+
|
| 777 |
+
# Set up keyboard shortcuts
|
| 778 |
+
key_bindings = self._merge_shortcuts(user_shortcuts=self.shortcuts)
|
| 779 |
+
|
| 780 |
+
# Pre-populate history from IPython's history database
|
| 781 |
+
history = PtkHistoryAdapter(self)
|
| 782 |
+
|
| 783 |
+
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
|
| 784 |
+
self.style = DynamicStyle(lambda: self._style)
|
| 785 |
+
|
| 786 |
+
editing_mode = getattr(EditingMode, self.editing_mode.upper())
|
| 787 |
+
|
| 788 |
+
self._use_asyncio_inputhook = False
|
| 789 |
+
self.pt_app = PromptSession(
|
| 790 |
+
auto_suggest=self.auto_suggest,
|
| 791 |
+
editing_mode=editing_mode,
|
| 792 |
+
key_bindings=key_bindings,
|
| 793 |
+
history=history,
|
| 794 |
+
completer=IPythonPTCompleter(shell=self),
|
| 795 |
+
enable_history_search=self.enable_history_search,
|
| 796 |
+
style=self.style,
|
| 797 |
+
include_default_pygments_style=False,
|
| 798 |
+
mouse_support=self.mouse_support,
|
| 799 |
+
enable_open_in_editor=self.extra_open_editor_shortcuts,
|
| 800 |
+
color_depth=self.color_depth,
|
| 801 |
+
tempfile_suffix=".py",
|
| 802 |
+
**self._extra_prompt_options(),
|
| 803 |
+
)
|
| 804 |
+
if isinstance(self.auto_suggest, NavigableAutoSuggestFromHistory):
|
| 805 |
+
self.auto_suggest.connect(self.pt_app)
|
| 806 |
+
|
| 807 |
+
def _make_style_from_name_or_cls(self, name_or_cls):
|
| 808 |
+
"""
|
| 809 |
+
Small wrapper that make an IPython compatible style from a style name
|
| 810 |
+
|
| 811 |
+
We need that to add style for prompt ... etc.
|
| 812 |
+
"""
|
| 813 |
+
style_overrides = {}
|
| 814 |
+
if name_or_cls == 'legacy':
|
| 815 |
+
legacy = self.colors.lower()
|
| 816 |
+
if legacy == 'linux':
|
| 817 |
+
style_cls = get_style_by_name('monokai')
|
| 818 |
+
style_overrides = _style_overrides_linux
|
| 819 |
+
elif legacy == 'lightbg':
|
| 820 |
+
style_overrides = _style_overrides_light_bg
|
| 821 |
+
style_cls = get_style_by_name('pastie')
|
| 822 |
+
elif legacy == 'neutral':
|
| 823 |
+
# The default theme needs to be visible on both a dark background
|
| 824 |
+
# and a light background, because we can't tell what the terminal
|
| 825 |
+
# looks like. These tweaks to the default theme help with that.
|
| 826 |
+
style_cls = get_style_by_name('default')
|
| 827 |
+
style_overrides.update({
|
| 828 |
+
Token.Number: '#ansigreen',
|
| 829 |
+
Token.Operator: 'noinherit',
|
| 830 |
+
Token.String: '#ansiyellow',
|
| 831 |
+
Token.Name.Function: '#ansiblue',
|
| 832 |
+
Token.Name.Class: 'bold #ansiblue',
|
| 833 |
+
Token.Name.Namespace: 'bold #ansiblue',
|
| 834 |
+
Token.Name.Variable.Magic: '#ansiblue',
|
| 835 |
+
Token.Prompt: '#ansigreen',
|
| 836 |
+
Token.PromptNum: '#ansibrightgreen bold',
|
| 837 |
+
Token.OutPrompt: '#ansired',
|
| 838 |
+
Token.OutPromptNum: '#ansibrightred bold',
|
| 839 |
+
})
|
| 840 |
+
|
| 841 |
+
# Hack: Due to limited color support on the Windows console
|
| 842 |
+
# the prompt colors will be wrong without this
|
| 843 |
+
if os.name == 'nt':
|
| 844 |
+
style_overrides.update({
|
| 845 |
+
Token.Prompt: '#ansidarkgreen',
|
| 846 |
+
Token.PromptNum: '#ansigreen bold',
|
| 847 |
+
Token.OutPrompt: '#ansidarkred',
|
| 848 |
+
Token.OutPromptNum: '#ansired bold',
|
| 849 |
+
})
|
| 850 |
+
elif legacy =='nocolor':
|
| 851 |
+
style_cls=_NoStyle
|
| 852 |
+
style_overrides = {}
|
| 853 |
+
else :
|
| 854 |
+
raise ValueError('Got unknown colors: ', legacy)
|
| 855 |
+
else :
|
| 856 |
+
if isinstance(name_or_cls, str):
|
| 857 |
+
style_cls = get_style_by_name(name_or_cls)
|
| 858 |
+
else:
|
| 859 |
+
style_cls = name_or_cls
|
| 860 |
+
style_overrides = {
|
| 861 |
+
Token.Prompt: '#ansigreen',
|
| 862 |
+
Token.PromptNum: '#ansibrightgreen bold',
|
| 863 |
+
Token.OutPrompt: '#ansired',
|
| 864 |
+
Token.OutPromptNum: '#ansibrightred bold',
|
| 865 |
+
}
|
| 866 |
+
style_overrides.update(self.highlighting_style_overrides)
|
| 867 |
+
style = merge_styles([
|
| 868 |
+
style_from_pygments_cls(style_cls),
|
| 869 |
+
style_from_pygments_dict(style_overrides),
|
| 870 |
+
])
|
| 871 |
+
|
| 872 |
+
return style
|
| 873 |
+
|
| 874 |
+
@property
|
| 875 |
+
def pt_complete_style(self):
|
| 876 |
+
return {
|
| 877 |
+
'multicolumn': CompleteStyle.MULTI_COLUMN,
|
| 878 |
+
'column': CompleteStyle.COLUMN,
|
| 879 |
+
'readlinelike': CompleteStyle.READLINE_LIKE,
|
| 880 |
+
}[self.display_completions]
|
| 881 |
+
|
| 882 |
+
@property
|
| 883 |
+
def color_depth(self):
|
| 884 |
+
return (ColorDepth.TRUE_COLOR if self.true_color else None)
|
| 885 |
+
|
| 886 |
+
def _extra_prompt_options(self):
|
| 887 |
+
"""
|
| 888 |
+
Return the current layout option for the current Terminal InteractiveShell
|
| 889 |
+
"""
|
| 890 |
+
def get_message():
|
| 891 |
+
return PygmentsTokens(self.prompts.in_prompt_tokens())
|
| 892 |
+
|
| 893 |
+
if self.editing_mode == "emacs" and self.prompt_line_number_format == "":
|
| 894 |
+
# with emacs mode the prompt is (usually) static, so we call only
|
| 895 |
+
# the function once. With VI mode it can toggle between [ins] and
|
| 896 |
+
# [nor] so we can't precompute.
|
| 897 |
+
# here I'm going to favor the default keybinding which almost
|
| 898 |
+
# everybody uses to decrease CPU usage.
|
| 899 |
+
# if we have issues with users with custom Prompts we can see how to
|
| 900 |
+
# work around this.
|
| 901 |
+
get_message = get_message()
|
| 902 |
+
|
| 903 |
+
options = {
|
| 904 |
+
"complete_in_thread": False,
|
| 905 |
+
"lexer": IPythonPTLexer(),
|
| 906 |
+
"reserve_space_for_menu": self.space_for_menu,
|
| 907 |
+
"message": get_message,
|
| 908 |
+
"prompt_continuation": (
|
| 909 |
+
lambda width, lineno, is_soft_wrap: PygmentsTokens(
|
| 910 |
+
_backward_compat_continuation_prompt_tokens(
|
| 911 |
+
self.prompts.continuation_prompt_tokens, width, lineno=lineno
|
| 912 |
+
)
|
| 913 |
+
)
|
| 914 |
+
),
|
| 915 |
+
"multiline": True,
|
| 916 |
+
"complete_style": self.pt_complete_style,
|
| 917 |
+
"input_processors": [
|
| 918 |
+
# Highlight matching brackets, but only when this setting is
|
| 919 |
+
# enabled, and only when the DEFAULT_BUFFER has the focus.
|
| 920 |
+
ConditionalProcessor(
|
| 921 |
+
processor=HighlightMatchingBracketProcessor(chars="[](){}"),
|
| 922 |
+
filter=HasFocus(DEFAULT_BUFFER)
|
| 923 |
+
& ~IsDone()
|
| 924 |
+
& Condition(lambda: self.highlight_matching_brackets),
|
| 925 |
+
),
|
| 926 |
+
# Show auto-suggestion in lines other than the last line.
|
| 927 |
+
ConditionalProcessor(
|
| 928 |
+
processor=AppendAutoSuggestionInAnyLine(),
|
| 929 |
+
filter=HasFocus(DEFAULT_BUFFER)
|
| 930 |
+
& ~IsDone()
|
| 931 |
+
& Condition(
|
| 932 |
+
lambda: isinstance(
|
| 933 |
+
self.auto_suggest,
|
| 934 |
+
NavigableAutoSuggestFromHistory,
|
| 935 |
+
)
|
| 936 |
+
),
|
| 937 |
+
),
|
| 938 |
+
],
|
| 939 |
+
}
|
| 940 |
+
if not PTK3:
|
| 941 |
+
options['inputhook'] = self.inputhook
|
| 942 |
+
|
| 943 |
+
return options
|
| 944 |
+
|
| 945 |
+
def prompt_for_code(self):
|
| 946 |
+
if self.rl_next_input:
|
| 947 |
+
default = self.rl_next_input
|
| 948 |
+
self.rl_next_input = None
|
| 949 |
+
else:
|
| 950 |
+
default = ''
|
| 951 |
+
|
| 952 |
+
# In order to make sure that asyncio code written in the
|
| 953 |
+
# interactive shell doesn't interfere with the prompt, we run the
|
| 954 |
+
# prompt in a different event loop.
|
| 955 |
+
# If we don't do this, people could spawn coroutine with a
|
| 956 |
+
# while/true inside which will freeze the prompt.
|
| 957 |
+
|
| 958 |
+
with patch_stdout(raw=True):
|
| 959 |
+
if self._use_asyncio_inputhook:
|
| 960 |
+
# When we integrate the asyncio event loop, run the UI in the
|
| 961 |
+
# same event loop as the rest of the code. don't use an actual
|
| 962 |
+
# input hook. (Asyncio is not made for nesting event loops.)
|
| 963 |
+
asyncio_loop = get_asyncio_loop()
|
| 964 |
+
text = asyncio_loop.run_until_complete(
|
| 965 |
+
self.pt_app.prompt_async(
|
| 966 |
+
default=default, **self._extra_prompt_options()
|
| 967 |
+
)
|
| 968 |
+
)
|
| 969 |
+
else:
|
| 970 |
+
text = self.pt_app.prompt(
|
| 971 |
+
default=default,
|
| 972 |
+
inputhook=self._inputhook,
|
| 973 |
+
**self._extra_prompt_options(),
|
| 974 |
+
)
|
| 975 |
+
|
| 976 |
+
return text
|
| 977 |
+
|
| 978 |
+
def enable_win_unicode_console(self):
|
| 979 |
+
# Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
|
| 980 |
+
# console by default, so WUC shouldn't be needed.
|
| 981 |
+
warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
|
| 982 |
+
DeprecationWarning,
|
| 983 |
+
stacklevel=2)
|
| 984 |
+
|
| 985 |
+
def init_io(self):
|
| 986 |
+
if sys.platform not in {'win32', 'cli'}:
|
| 987 |
+
return
|
| 988 |
+
|
| 989 |
+
import colorama
|
| 990 |
+
colorama.init()
|
| 991 |
+
|
| 992 |
+
def init_magics(self):
|
| 993 |
+
super(TerminalInteractiveShell, self).init_magics()
|
| 994 |
+
self.register_magics(TerminalMagics)
|
| 995 |
+
|
| 996 |
+
def init_alias(self):
|
| 997 |
+
# The parent class defines aliases that can be safely used with any
|
| 998 |
+
# frontend.
|
| 999 |
+
super(TerminalInteractiveShell, self).init_alias()
|
| 1000 |
+
|
| 1001 |
+
# Now define aliases that only make sense on the terminal, because they
|
| 1002 |
+
# need direct access to the console in a way that we can't emulate in
|
| 1003 |
+
# GUI or web frontend
|
| 1004 |
+
if os.name == 'posix':
|
| 1005 |
+
for cmd in ('clear', 'more', 'less', 'man'):
|
| 1006 |
+
self.alias_manager.soft_define_alias(cmd, cmd)
|
| 1007 |
+
|
| 1008 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 1009 |
+
super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
|
| 1010 |
+
self._set_autosuggestions(self.autosuggestions_provider)
|
| 1011 |
+
self.init_prompt_toolkit_cli()
|
| 1012 |
+
self.init_term_title()
|
| 1013 |
+
self.keep_running = True
|
| 1014 |
+
self._set_formatter(self.autoformatter)
|
| 1015 |
+
|
| 1016 |
+
def ask_exit(self):
|
| 1017 |
+
self.keep_running = False
|
| 1018 |
+
|
| 1019 |
+
rl_next_input = None
|
| 1020 |
+
|
| 1021 |
+
def interact(self):
|
| 1022 |
+
self.keep_running = True
|
| 1023 |
+
while self.keep_running:
|
| 1024 |
+
print(self.separate_in, end='')
|
| 1025 |
+
|
| 1026 |
+
try:
|
| 1027 |
+
code = self.prompt_for_code()
|
| 1028 |
+
except EOFError:
|
| 1029 |
+
if (not self.confirm_exit) \
|
| 1030 |
+
or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
|
| 1031 |
+
self.ask_exit()
|
| 1032 |
+
|
| 1033 |
+
else:
|
| 1034 |
+
if code:
|
| 1035 |
+
self.run_cell(code, store_history=True)
|
| 1036 |
+
|
| 1037 |
+
def mainloop(self):
|
| 1038 |
+
# An extra layer of protection in case someone mashing Ctrl-C breaks
|
| 1039 |
+
# out of our internal code.
|
| 1040 |
+
while True:
|
| 1041 |
+
try:
|
| 1042 |
+
self.interact()
|
| 1043 |
+
break
|
| 1044 |
+
except KeyboardInterrupt as e:
|
| 1045 |
+
print("\n%s escaped interact()\n" % type(e).__name__)
|
| 1046 |
+
finally:
|
| 1047 |
+
# An interrupt during the eventloop will mess up the
|
| 1048 |
+
# internal state of the prompt_toolkit library.
|
| 1049 |
+
# Stopping the eventloop fixes this, see
|
| 1050 |
+
# https://github.com/ipython/ipython/pull/9867
|
| 1051 |
+
if hasattr(self, '_eventloop'):
|
| 1052 |
+
self._eventloop.stop()
|
| 1053 |
+
|
| 1054 |
+
self.restore_term_title()
|
| 1055 |
+
|
| 1056 |
+
# try to call some at-exit operation optimistically as some things can't
|
| 1057 |
+
# be done during interpreter shutdown. this is technically inaccurate as
|
| 1058 |
+
# this make mainlool not re-callable, but that should be a rare if not
|
| 1059 |
+
# in existent use case.
|
| 1060 |
+
|
| 1061 |
+
self._atexit_once()
|
| 1062 |
+
|
| 1063 |
+
_inputhook = None
|
| 1064 |
+
def inputhook(self, context):
|
| 1065 |
+
if self._inputhook is not None:
|
| 1066 |
+
self._inputhook(context)
|
| 1067 |
+
|
| 1068 |
+
active_eventloop: Optional[str] = None
|
| 1069 |
+
|
| 1070 |
+
def enable_gui(self, gui: Optional[str] = None) -> None:
|
| 1071 |
+
if gui:
|
| 1072 |
+
from ..core.pylabtools import _convert_gui_from_matplotlib
|
| 1073 |
+
|
| 1074 |
+
gui = _convert_gui_from_matplotlib(gui)
|
| 1075 |
+
|
| 1076 |
+
if self.simple_prompt is True and gui is not None:
|
| 1077 |
+
print(
|
| 1078 |
+
f'Cannot install event loop hook for "{gui}" when running with `--simple-prompt`.'
|
| 1079 |
+
)
|
| 1080 |
+
print(
|
| 1081 |
+
"NOTE: Tk is supported natively; use Tk apps and Tk backends with `--simple-prompt`."
|
| 1082 |
+
)
|
| 1083 |
+
return
|
| 1084 |
+
|
| 1085 |
+
if self._inputhook is None and gui is None:
|
| 1086 |
+
print("No event loop hook running.")
|
| 1087 |
+
return
|
| 1088 |
+
|
| 1089 |
+
if self._inputhook is not None and gui is not None:
|
| 1090 |
+
newev, newinhook = get_inputhook_name_and_func(gui)
|
| 1091 |
+
if self._inputhook == newinhook:
|
| 1092 |
+
# same inputhook, do nothing
|
| 1093 |
+
self.log.info(
|
| 1094 |
+
f"Shell is already running the {self.active_eventloop} eventloop. Doing nothing"
|
| 1095 |
+
)
|
| 1096 |
+
return
|
| 1097 |
+
self.log.warning(
|
| 1098 |
+
f"Shell is already running a different gui event loop for {self.active_eventloop}. "
|
| 1099 |
+
"Call with no arguments to disable the current loop."
|
| 1100 |
+
)
|
| 1101 |
+
return
|
| 1102 |
+
if self._inputhook is not None and gui is None:
|
| 1103 |
+
self.active_eventloop = self._inputhook = None
|
| 1104 |
+
|
| 1105 |
+
if gui and (gui not in {None, "webagg"}):
|
| 1106 |
+
# This hook runs with each cycle of the `prompt_toolkit`'s event loop.
|
| 1107 |
+
self.active_eventloop, self._inputhook = get_inputhook_name_and_func(gui)
|
| 1108 |
+
else:
|
| 1109 |
+
self.active_eventloop = self._inputhook = None
|
| 1110 |
+
|
| 1111 |
+
self._use_asyncio_inputhook = gui == "asyncio"
|
| 1112 |
+
|
| 1113 |
+
# Run !system commands directly, not through pipes, so terminal programs
|
| 1114 |
+
# work correctly.
|
| 1115 |
+
system = InteractiveShell.system_raw
|
| 1116 |
+
|
| 1117 |
+
def auto_rewrite_input(self, cmd):
|
| 1118 |
+
"""Overridden from the parent class to use fancy rewriting prompt"""
|
| 1119 |
+
if not self.show_rewritten_input:
|
| 1120 |
+
return
|
| 1121 |
+
|
| 1122 |
+
tokens = self.prompts.rewrite_prompt_tokens()
|
| 1123 |
+
if self.pt_app:
|
| 1124 |
+
print_formatted_text(PygmentsTokens(tokens), end='',
|
| 1125 |
+
style=self.pt_app.app.style)
|
| 1126 |
+
print(cmd)
|
| 1127 |
+
else:
|
| 1128 |
+
prompt = ''.join(s for t, s in tokens)
|
| 1129 |
+
print(prompt, cmd, sep='')
|
| 1130 |
+
|
| 1131 |
+
_prompts_before = None
|
| 1132 |
+
def switch_doctest_mode(self, mode):
|
| 1133 |
+
"""Switch prompts to classic for %doctest_mode"""
|
| 1134 |
+
if mode:
|
| 1135 |
+
self._prompts_before = self.prompts
|
| 1136 |
+
self.prompts = ClassicPrompts(self)
|
| 1137 |
+
elif self._prompts_before:
|
| 1138 |
+
self.prompts = self._prompts_before
|
| 1139 |
+
self._prompts_before = None
|
| 1140 |
+
# self._update_layout()
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
InteractiveShellABC.register(TerminalInteractiveShell)
|
| 1144 |
+
|
| 1145 |
+
if __name__ == '__main__':
|
| 1146 |
+
TerminalInteractiveShell.instance().interact()
|
material/dataset/xpsdee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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# encoding: utf-8
|
| 2 |
+
"""
|
| 3 |
+
The :class:`~traitlets.config.application.Application` object for the command
|
| 4 |
+
line :command:`ipython` program.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
# Copyright (c) IPython Development Team.
|
| 8 |
+
# Distributed under the terms of the Modified BSD License.
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
from traitlets.config.loader import Config
|
| 17 |
+
from traitlets.config.application import boolean_flag, catch_config_error
|
| 18 |
+
from IPython.core import release
|
| 19 |
+
from IPython.core import usage
|
| 20 |
+
from IPython.core.completer import IPCompleter
|
| 21 |
+
from IPython.core.crashhandler import CrashHandler
|
| 22 |
+
from IPython.core.formatters import PlainTextFormatter
|
| 23 |
+
from IPython.core.history import HistoryManager
|
| 24 |
+
from IPython.core.application import (
|
| 25 |
+
ProfileDir, BaseIPythonApplication, base_flags, base_aliases
|
| 26 |
+
)
|
| 27 |
+
from IPython.core.magic import MagicsManager
|
| 28 |
+
from IPython.core.magics import (
|
| 29 |
+
ScriptMagics, LoggingMagics
|
| 30 |
+
)
|
| 31 |
+
from IPython.core.shellapp import (
|
| 32 |
+
InteractiveShellApp, shell_flags, shell_aliases
|
| 33 |
+
)
|
| 34 |
+
from IPython.extensions.storemagic import StoreMagics
|
| 35 |
+
from .interactiveshell import TerminalInteractiveShell
|
| 36 |
+
from IPython.paths import get_ipython_dir
|
| 37 |
+
from traitlets import (
|
| 38 |
+
Bool, List, default, observe, Type
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
#-----------------------------------------------------------------------------
|
| 42 |
+
# Globals, utilities and helpers
|
| 43 |
+
#-----------------------------------------------------------------------------
|
| 44 |
+
|
| 45 |
+
_examples = """
|
| 46 |
+
ipython --matplotlib # enable matplotlib integration
|
| 47 |
+
ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
|
| 48 |
+
|
| 49 |
+
ipython --log-level=DEBUG # set logging to DEBUG
|
| 50 |
+
ipython --profile=foo # start with profile foo
|
| 51 |
+
|
| 52 |
+
ipython profile create foo # create profile foo w/ default config files
|
| 53 |
+
ipython help profile # show the help for the profile subcmd
|
| 54 |
+
|
| 55 |
+
ipython locate # print the path to the IPython directory
|
| 56 |
+
ipython locate profile foo # print the path to the directory for profile `foo`
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
#-----------------------------------------------------------------------------
|
| 60 |
+
# Crash handler for this application
|
| 61 |
+
#-----------------------------------------------------------------------------
|
| 62 |
+
|
| 63 |
+
class IPAppCrashHandler(CrashHandler):
|
| 64 |
+
"""sys.excepthook for IPython itself, leaves a detailed report on disk."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, app):
|
| 67 |
+
contact_name = release.author
|
| 68 |
+
contact_email = release.author_email
|
| 69 |
+
bug_tracker = 'https://github.com/ipython/ipython/issues'
|
| 70 |
+
super(IPAppCrashHandler,self).__init__(
|
| 71 |
+
app, contact_name, contact_email, bug_tracker
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def make_report(self,traceback):
|
| 75 |
+
"""Return a string containing a crash report."""
|
| 76 |
+
|
| 77 |
+
sec_sep = self.section_sep
|
| 78 |
+
# Start with parent report
|
| 79 |
+
report = [super(IPAppCrashHandler, self).make_report(traceback)]
|
| 80 |
+
# Add interactive-specific info we may have
|
| 81 |
+
rpt_add = report.append
|
| 82 |
+
try:
|
| 83 |
+
rpt_add(sec_sep+"History of session input:")
|
| 84 |
+
for line in self.app.shell.user_ns['_ih']:
|
| 85 |
+
rpt_add(line)
|
| 86 |
+
rpt_add('\n*** Last line of input (may not be in above history):\n')
|
| 87 |
+
rpt_add(self.app.shell._last_input_line+'\n')
|
| 88 |
+
except:
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
return ''.join(report)
|
| 92 |
+
|
| 93 |
+
#-----------------------------------------------------------------------------
|
| 94 |
+
# Aliases and Flags
|
| 95 |
+
#-----------------------------------------------------------------------------
|
| 96 |
+
flags = dict(base_flags)
|
| 97 |
+
flags.update(shell_flags)
|
| 98 |
+
frontend_flags = {}
|
| 99 |
+
addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
|
| 100 |
+
addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
|
| 101 |
+
'Turn on auto editing of files with syntax errors.',
|
| 102 |
+
'Turn off auto editing of files with syntax errors.'
|
| 103 |
+
)
|
| 104 |
+
addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
|
| 105 |
+
"Force simple minimal prompt using `raw_input`",
|
| 106 |
+
"Use a rich interactive prompt with prompt_toolkit",
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
addflag('banner', 'TerminalIPythonApp.display_banner',
|
| 110 |
+
"Display a banner upon starting IPython.",
|
| 111 |
+
"Don't display a banner upon starting IPython."
|
| 112 |
+
)
|
| 113 |
+
addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
|
| 114 |
+
"""Set to confirm when you try to exit IPython with an EOF (Control-D
|
| 115 |
+
in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
|
| 116 |
+
you can force a direct exit without any confirmation.""",
|
| 117 |
+
"Don't prompt the user when exiting."
|
| 118 |
+
)
|
| 119 |
+
addflag('term-title', 'TerminalInteractiveShell.term_title',
|
| 120 |
+
"Enable auto setting the terminal title.",
|
| 121 |
+
"Disable auto setting the terminal title."
|
| 122 |
+
)
|
| 123 |
+
classic_config = Config()
|
| 124 |
+
classic_config.InteractiveShell.cache_size = 0
|
| 125 |
+
classic_config.PlainTextFormatter.pprint = False
|
| 126 |
+
classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
|
| 127 |
+
classic_config.InteractiveShell.separate_in = ''
|
| 128 |
+
classic_config.InteractiveShell.separate_out = ''
|
| 129 |
+
classic_config.InteractiveShell.separate_out2 = ''
|
| 130 |
+
classic_config.InteractiveShell.colors = 'NoColor'
|
| 131 |
+
classic_config.InteractiveShell.xmode = 'Plain'
|
| 132 |
+
|
| 133 |
+
frontend_flags['classic']=(
|
| 134 |
+
classic_config,
|
| 135 |
+
"Gives IPython a similar feel to the classic Python prompt."
|
| 136 |
+
)
|
| 137 |
+
# # log doesn't make so much sense this way anymore
|
| 138 |
+
# paa('--log','-l',
|
| 139 |
+
# action='store_true', dest='InteractiveShell.logstart',
|
| 140 |
+
# help="Start logging to the default log file (./ipython_log.py).")
|
| 141 |
+
#
|
| 142 |
+
# # quick is harder to implement
|
| 143 |
+
frontend_flags['quick']=(
|
| 144 |
+
{'TerminalIPythonApp' : {'quick' : True}},
|
| 145 |
+
"Enable quick startup with no config files."
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
frontend_flags['i'] = (
|
| 149 |
+
{'TerminalIPythonApp' : {'force_interact' : True}},
|
| 150 |
+
"""If running code from the command line, become interactive afterwards.
|
| 151 |
+
It is often useful to follow this with `--` to treat remaining flags as
|
| 152 |
+
script arguments.
|
| 153 |
+
"""
|
| 154 |
+
)
|
| 155 |
+
flags.update(frontend_flags)
|
| 156 |
+
|
| 157 |
+
aliases = dict(base_aliases)
|
| 158 |
+
aliases.update(shell_aliases) # type: ignore[arg-type]
|
| 159 |
+
|
| 160 |
+
#-----------------------------------------------------------------------------
|
| 161 |
+
# Main classes and functions
|
| 162 |
+
#-----------------------------------------------------------------------------
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class LocateIPythonApp(BaseIPythonApplication):
|
| 166 |
+
description = """print the path to the IPython dir"""
|
| 167 |
+
subcommands = dict(
|
| 168 |
+
profile=('IPython.core.profileapp.ProfileLocate',
|
| 169 |
+
"print the path to an IPython profile directory",
|
| 170 |
+
),
|
| 171 |
+
)
|
| 172 |
+
def start(self):
|
| 173 |
+
if self.subapp is not None:
|
| 174 |
+
return self.subapp.start()
|
| 175 |
+
else:
|
| 176 |
+
print(self.ipython_dir)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
|
| 180 |
+
name = "ipython"
|
| 181 |
+
description = usage.cl_usage
|
| 182 |
+
crash_handler_class = IPAppCrashHandler # typing: ignore[assignment]
|
| 183 |
+
examples = _examples
|
| 184 |
+
|
| 185 |
+
flags = flags
|
| 186 |
+
aliases = aliases
|
| 187 |
+
classes = List()
|
| 188 |
+
|
| 189 |
+
interactive_shell_class = Type(
|
| 190 |
+
klass=object, # use default_value otherwise which only allow subclasses.
|
| 191 |
+
default_value=TerminalInteractiveShell,
|
| 192 |
+
help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
|
| 193 |
+
).tag(config=True)
|
| 194 |
+
|
| 195 |
+
@default('classes')
|
| 196 |
+
def _classes_default(self):
|
| 197 |
+
"""This has to be in a method, for TerminalIPythonApp to be available."""
|
| 198 |
+
return [
|
| 199 |
+
InteractiveShellApp, # ShellApp comes before TerminalApp, because
|
| 200 |
+
self.__class__, # it will also affect subclasses (e.g. QtConsole)
|
| 201 |
+
TerminalInteractiveShell,
|
| 202 |
+
HistoryManager,
|
| 203 |
+
MagicsManager,
|
| 204 |
+
ProfileDir,
|
| 205 |
+
PlainTextFormatter,
|
| 206 |
+
IPCompleter,
|
| 207 |
+
ScriptMagics,
|
| 208 |
+
LoggingMagics,
|
| 209 |
+
StoreMagics,
|
| 210 |
+
]
|
| 211 |
+
|
| 212 |
+
subcommands = dict(
|
| 213 |
+
profile = ("IPython.core.profileapp.ProfileApp",
|
| 214 |
+
"Create and manage IPython profiles."
|
| 215 |
+
),
|
| 216 |
+
kernel = ("ipykernel.kernelapp.IPKernelApp",
|
| 217 |
+
"Start a kernel without an attached frontend."
|
| 218 |
+
),
|
| 219 |
+
locate=('IPython.terminal.ipapp.LocateIPythonApp',
|
| 220 |
+
LocateIPythonApp.description
|
| 221 |
+
),
|
| 222 |
+
history=('IPython.core.historyapp.HistoryApp',
|
| 223 |
+
"Manage the IPython history database."
|
| 224 |
+
),
|
| 225 |
+
)
|
| 226 |
+
|
| 227 |
+
# *do* autocreate requested profile, but don't create the config file.
|
| 228 |
+
auto_create = Bool(True).tag(config=True)
|
| 229 |
+
|
| 230 |
+
# configurables
|
| 231 |
+
quick = Bool(False,
|
| 232 |
+
help="""Start IPython quickly by skipping the loading of config files."""
|
| 233 |
+
).tag(config=True)
|
| 234 |
+
@observe('quick')
|
| 235 |
+
def _quick_changed(self, change):
|
| 236 |
+
if change['new']:
|
| 237 |
+
self.load_config_file = lambda *a, **kw: None
|
| 238 |
+
|
| 239 |
+
display_banner = Bool(True,
|
| 240 |
+
help="Whether to display a banner upon starting IPython."
|
| 241 |
+
).tag(config=True)
|
| 242 |
+
|
| 243 |
+
# if there is code of files to run from the cmd line, don't interact
|
| 244 |
+
# unless the --i flag (App.force_interact) is true.
|
| 245 |
+
force_interact = Bool(False,
|
| 246 |
+
help="""If a command or file is given via the command-line,
|
| 247 |
+
e.g. 'ipython foo.py', start an interactive shell after executing the
|
| 248 |
+
file or command."""
|
| 249 |
+
).tag(config=True)
|
| 250 |
+
@observe('force_interact')
|
| 251 |
+
def _force_interact_changed(self, change):
|
| 252 |
+
if change['new']:
|
| 253 |
+
self.interact = True
|
| 254 |
+
|
| 255 |
+
@observe('file_to_run', 'code_to_run', 'module_to_run')
|
| 256 |
+
def _file_to_run_changed(self, change):
|
| 257 |
+
new = change['new']
|
| 258 |
+
if new:
|
| 259 |
+
self.something_to_run = True
|
| 260 |
+
if new and not self.force_interact:
|
| 261 |
+
self.interact = False
|
| 262 |
+
|
| 263 |
+
# internal, not-configurable
|
| 264 |
+
something_to_run=Bool(False)
|
| 265 |
+
|
| 266 |
+
@catch_config_error
|
| 267 |
+
def initialize(self, argv=None):
|
| 268 |
+
"""Do actions after construct, but before starting the app."""
|
| 269 |
+
super(TerminalIPythonApp, self).initialize(argv)
|
| 270 |
+
if self.subapp is not None:
|
| 271 |
+
# don't bother initializing further, starting subapp
|
| 272 |
+
return
|
| 273 |
+
# print(self.extra_args)
|
| 274 |
+
if self.extra_args and not self.something_to_run:
|
| 275 |
+
self.file_to_run = self.extra_args[0]
|
| 276 |
+
self.init_path()
|
| 277 |
+
# create the shell
|
| 278 |
+
self.init_shell()
|
| 279 |
+
# and draw the banner
|
| 280 |
+
self.init_banner()
|
| 281 |
+
# Now a variety of things that happen after the banner is printed.
|
| 282 |
+
self.init_gui_pylab()
|
| 283 |
+
self.init_extensions()
|
| 284 |
+
self.init_code()
|
| 285 |
+
|
| 286 |
+
def init_shell(self):
|
| 287 |
+
"""initialize the InteractiveShell instance"""
|
| 288 |
+
# Create an InteractiveShell instance.
|
| 289 |
+
# shell.display_banner should always be False for the terminal
|
| 290 |
+
# based app, because we call shell.show_banner() by hand below
|
| 291 |
+
# so the banner shows *before* all extension loading stuff.
|
| 292 |
+
self.shell = self.interactive_shell_class.instance(parent=self,
|
| 293 |
+
profile_dir=self.profile_dir,
|
| 294 |
+
ipython_dir=self.ipython_dir, user_ns=self.user_ns)
|
| 295 |
+
self.shell.configurables.append(self)
|
| 296 |
+
|
| 297 |
+
def init_banner(self):
|
| 298 |
+
"""optionally display the banner"""
|
| 299 |
+
if self.display_banner and self.interact:
|
| 300 |
+
self.shell.show_banner()
|
| 301 |
+
# Make sure there is a space below the banner.
|
| 302 |
+
if self.log_level <= logging.INFO: print()
|
| 303 |
+
|
| 304 |
+
def _pylab_changed(self, name, old, new):
|
| 305 |
+
"""Replace --pylab='inline' with --pylab='auto'"""
|
| 306 |
+
if new == 'inline':
|
| 307 |
+
warnings.warn("'inline' not available as pylab backend, "
|
| 308 |
+
"using 'auto' instead.")
|
| 309 |
+
self.pylab = 'auto'
|
| 310 |
+
|
| 311 |
+
def start(self):
|
| 312 |
+
if self.subapp is not None:
|
| 313 |
+
return self.subapp.start()
|
| 314 |
+
# perform any prexec steps:
|
| 315 |
+
if self.interact:
|
| 316 |
+
self.log.debug("Starting IPython's mainloop...")
|
| 317 |
+
self.shell.mainloop()
|
| 318 |
+
else:
|
| 319 |
+
self.log.debug("IPython not interactive...")
|
| 320 |
+
self.shell.restore_term_title()
|
| 321 |
+
if not self.shell.last_execution_succeeded:
|
| 322 |
+
sys.exit(1)
|
| 323 |
+
|
| 324 |
+
def load_default_config(ipython_dir=None):
|
| 325 |
+
"""Load the default config file from the default ipython_dir.
|
| 326 |
+
|
| 327 |
+
This is useful for embedded shells.
|
| 328 |
+
"""
|
| 329 |
+
if ipython_dir is None:
|
| 330 |
+
ipython_dir = get_ipython_dir()
|
| 331 |
+
|
| 332 |
+
profile_dir = os.path.join(ipython_dir, 'profile_default')
|
| 333 |
+
app = TerminalIPythonApp()
|
| 334 |
+
app.config_file_paths.append(profile_dir)
|
| 335 |
+
app.load_config_file()
|
| 336 |
+
return app.config
|
| 337 |
+
|
| 338 |
+
launch_new_instance = TerminalIPythonApp.launch_instance
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/magics.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extra magics for terminal use."""
|
| 2 |
+
|
| 3 |
+
# Copyright (c) IPython Development Team.
|
| 4 |
+
# Distributed under the terms of the Modified BSD License.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
from logging import error
|
| 8 |
+
import os
|
| 9 |
+
import sys
|
| 10 |
+
|
| 11 |
+
from IPython.core.error import TryNext, UsageError
|
| 12 |
+
from IPython.core.magic import Magics, magics_class, line_magic
|
| 13 |
+
from IPython.lib.clipboard import ClipboardEmpty
|
| 14 |
+
from IPython.testing.skipdoctest import skip_doctest
|
| 15 |
+
from IPython.utils.text import SList, strip_email_quotes
|
| 16 |
+
from IPython.utils import py3compat
|
| 17 |
+
|
| 18 |
+
def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
|
| 19 |
+
""" Yield pasted lines until the user enters the given sentinel value.
|
| 20 |
+
"""
|
| 21 |
+
if not quiet:
|
| 22 |
+
print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
|
| 23 |
+
% sentinel)
|
| 24 |
+
prompt = ":"
|
| 25 |
+
else:
|
| 26 |
+
prompt = ""
|
| 27 |
+
while True:
|
| 28 |
+
try:
|
| 29 |
+
l = l_input(prompt)
|
| 30 |
+
if l == sentinel:
|
| 31 |
+
return
|
| 32 |
+
else:
|
| 33 |
+
yield l
|
| 34 |
+
except EOFError:
|
| 35 |
+
print('<EOF>')
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@magics_class
|
| 40 |
+
class TerminalMagics(Magics):
|
| 41 |
+
def __init__(self, shell):
|
| 42 |
+
super(TerminalMagics, self).__init__(shell)
|
| 43 |
+
|
| 44 |
+
def store_or_execute(self, block, name, store_history=False):
|
| 45 |
+
""" Execute a block, or store it in a variable, per the user's request.
|
| 46 |
+
"""
|
| 47 |
+
if name:
|
| 48 |
+
# If storing it for further editing
|
| 49 |
+
self.shell.user_ns[name] = SList(block.splitlines())
|
| 50 |
+
print("Block assigned to '%s'" % name)
|
| 51 |
+
else:
|
| 52 |
+
b = self.preclean_input(block)
|
| 53 |
+
self.shell.user_ns['pasted_block'] = b
|
| 54 |
+
self.shell.using_paste_magics = True
|
| 55 |
+
try:
|
| 56 |
+
self.shell.run_cell(b, store_history)
|
| 57 |
+
finally:
|
| 58 |
+
self.shell.using_paste_magics = False
|
| 59 |
+
|
| 60 |
+
def preclean_input(self, block):
|
| 61 |
+
lines = block.splitlines()
|
| 62 |
+
while lines and not lines[0].strip():
|
| 63 |
+
lines = lines[1:]
|
| 64 |
+
return strip_email_quotes('\n'.join(lines))
|
| 65 |
+
|
| 66 |
+
def rerun_pasted(self, name='pasted_block'):
|
| 67 |
+
""" Rerun a previously pasted command.
|
| 68 |
+
"""
|
| 69 |
+
b = self.shell.user_ns.get(name)
|
| 70 |
+
|
| 71 |
+
# Sanity checks
|
| 72 |
+
if b is None:
|
| 73 |
+
raise UsageError('No previous pasted block available')
|
| 74 |
+
if not isinstance(b, str):
|
| 75 |
+
raise UsageError(
|
| 76 |
+
"Variable 'pasted_block' is not a string, can't execute")
|
| 77 |
+
|
| 78 |
+
print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
|
| 79 |
+
self.shell.run_cell(b)
|
| 80 |
+
|
| 81 |
+
@line_magic
|
| 82 |
+
def autoindent(self, parameter_s = ''):
|
| 83 |
+
"""Toggle autoindent on/off (deprecated)"""
|
| 84 |
+
self.shell.set_autoindent()
|
| 85 |
+
print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
|
| 86 |
+
|
| 87 |
+
@skip_doctest
|
| 88 |
+
@line_magic
|
| 89 |
+
def cpaste(self, parameter_s=''):
|
| 90 |
+
"""Paste & execute a pre-formatted code block from clipboard.
|
| 91 |
+
|
| 92 |
+
You must terminate the block with '--' (two minus-signs) or Ctrl-D
|
| 93 |
+
alone on the line. You can also provide your own sentinel with '%paste
|
| 94 |
+
-s %%' ('%%' is the new sentinel for this operation).
|
| 95 |
+
|
| 96 |
+
The block is dedented prior to execution to enable execution of method
|
| 97 |
+
definitions. '>' and '+' characters at the beginning of a line are
|
| 98 |
+
ignored, to allow pasting directly from e-mails, diff files and
|
| 99 |
+
doctests (the '...' continuation prompt is also stripped). The
|
| 100 |
+
executed block is also assigned to variable named 'pasted_block' for
|
| 101 |
+
later editing with '%edit pasted_block'.
|
| 102 |
+
|
| 103 |
+
You can also pass a variable name as an argument, e.g. '%cpaste foo'.
|
| 104 |
+
This assigns the pasted block to variable 'foo' as string, without
|
| 105 |
+
dedenting or executing it (preceding >>> and + is still stripped)
|
| 106 |
+
|
| 107 |
+
'%cpaste -r' re-executes the block previously entered by cpaste.
|
| 108 |
+
'%cpaste -q' suppresses any additional output messages.
|
| 109 |
+
|
| 110 |
+
Do not be alarmed by garbled output on Windows (it's a readline bug).
|
| 111 |
+
Just press enter and type -- (and press enter again) and the block
|
| 112 |
+
will be what was just pasted.
|
| 113 |
+
|
| 114 |
+
Shell escapes are not supported (yet).
|
| 115 |
+
|
| 116 |
+
See Also
|
| 117 |
+
--------
|
| 118 |
+
paste : automatically pull code from clipboard.
|
| 119 |
+
|
| 120 |
+
Examples
|
| 121 |
+
--------
|
| 122 |
+
::
|
| 123 |
+
|
| 124 |
+
In [8]: %cpaste
|
| 125 |
+
Pasting code; enter '--' alone on the line to stop.
|
| 126 |
+
:>>> a = ["world!", "Hello"]
|
| 127 |
+
:>>> print(" ".join(sorted(a)))
|
| 128 |
+
:--
|
| 129 |
+
Hello world!
|
| 130 |
+
|
| 131 |
+
::
|
| 132 |
+
In [8]: %cpaste
|
| 133 |
+
Pasting code; enter '--' alone on the line to stop.
|
| 134 |
+
:>>> %alias_magic t timeit
|
| 135 |
+
:>>> %t -n1 pass
|
| 136 |
+
:--
|
| 137 |
+
Created `%t` as an alias for `%timeit`.
|
| 138 |
+
Created `%%t` as an alias for `%%timeit`.
|
| 139 |
+
354 ns ± 224 ns per loop (mean ± std. dev. of 7 runs, 1 loop each)
|
| 140 |
+
"""
|
| 141 |
+
opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
|
| 142 |
+
if 'r' in opts:
|
| 143 |
+
self.rerun_pasted()
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
quiet = ('q' in opts)
|
| 147 |
+
|
| 148 |
+
sentinel = opts.get('s', u'--')
|
| 149 |
+
block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
|
| 150 |
+
self.store_or_execute(block, name, store_history=True)
|
| 151 |
+
|
| 152 |
+
@line_magic
|
| 153 |
+
def paste(self, parameter_s=''):
|
| 154 |
+
"""Paste & execute a pre-formatted code block from clipboard.
|
| 155 |
+
|
| 156 |
+
The text is pulled directly from the clipboard without user
|
| 157 |
+
intervention and printed back on the screen before execution (unless
|
| 158 |
+
the -q flag is given to force quiet mode).
|
| 159 |
+
|
| 160 |
+
The block is dedented prior to execution to enable execution of method
|
| 161 |
+
definitions. '>' and '+' characters at the beginning of a line are
|
| 162 |
+
ignored, to allow pasting directly from e-mails, diff files and
|
| 163 |
+
doctests (the '...' continuation prompt is also stripped). The
|
| 164 |
+
executed block is also assigned to variable named 'pasted_block' for
|
| 165 |
+
later editing with '%edit pasted_block'.
|
| 166 |
+
|
| 167 |
+
You can also pass a variable name as an argument, e.g. '%paste foo'.
|
| 168 |
+
This assigns the pasted block to variable 'foo' as string, without
|
| 169 |
+
executing it (preceding >>> and + is still stripped).
|
| 170 |
+
|
| 171 |
+
Options:
|
| 172 |
+
|
| 173 |
+
-r: re-executes the block previously entered by cpaste.
|
| 174 |
+
|
| 175 |
+
-q: quiet mode: do not echo the pasted text back to the terminal.
|
| 176 |
+
|
| 177 |
+
IPython statements (magics, shell escapes) are not supported (yet).
|
| 178 |
+
|
| 179 |
+
See Also
|
| 180 |
+
--------
|
| 181 |
+
cpaste : manually paste code into terminal until you mark its end.
|
| 182 |
+
"""
|
| 183 |
+
opts, name = self.parse_options(parameter_s, 'rq', mode='string')
|
| 184 |
+
if 'r' in opts:
|
| 185 |
+
self.rerun_pasted()
|
| 186 |
+
return
|
| 187 |
+
try:
|
| 188 |
+
block = self.shell.hooks.clipboard_get()
|
| 189 |
+
except TryNext as clipboard_exc:
|
| 190 |
+
message = getattr(clipboard_exc, 'args')
|
| 191 |
+
if message:
|
| 192 |
+
error(message[0])
|
| 193 |
+
else:
|
| 194 |
+
error('Could not get text from the clipboard.')
|
| 195 |
+
return
|
| 196 |
+
except ClipboardEmpty as e:
|
| 197 |
+
raise UsageError("The clipboard appears to be empty") from e
|
| 198 |
+
|
| 199 |
+
# By default, echo back to terminal unless quiet mode is requested
|
| 200 |
+
if 'q' not in opts:
|
| 201 |
+
sys.stdout.write(self.shell.pycolorize(block))
|
| 202 |
+
if not block.endswith("\n"):
|
| 203 |
+
sys.stdout.write("\n")
|
| 204 |
+
sys.stdout.write("## -- End pasted text --\n")
|
| 205 |
+
|
| 206 |
+
self.store_or_execute(block, name, store_history=True)
|
| 207 |
+
|
| 208 |
+
# Class-level: add a '%cls' magic only on Windows
|
| 209 |
+
if sys.platform == 'win32':
|
| 210 |
+
@line_magic
|
| 211 |
+
def cls(self, s):
|
| 212 |
+
"""Clear screen.
|
| 213 |
+
"""
|
| 214 |
+
os.system("cls")
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/prompts.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Terminal input and output prompts."""
|
| 2 |
+
|
| 3 |
+
from pygments.token import Token
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from IPython.core.displayhook import DisplayHook
|
| 7 |
+
|
| 8 |
+
from prompt_toolkit.formatted_text import fragment_list_width, PygmentsTokens
|
| 9 |
+
from prompt_toolkit.shortcuts import print_formatted_text
|
| 10 |
+
from prompt_toolkit.enums import EditingMode
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Prompts(object):
|
| 14 |
+
def __init__(self, shell):
|
| 15 |
+
self.shell = shell
|
| 16 |
+
|
| 17 |
+
def vi_mode(self):
|
| 18 |
+
if (getattr(self.shell.pt_app, 'editing_mode', None) == EditingMode.VI
|
| 19 |
+
and self.shell.prompt_includes_vi_mode):
|
| 20 |
+
mode = str(self.shell.pt_app.app.vi_state.input_mode)
|
| 21 |
+
if mode.startswith('InputMode.'):
|
| 22 |
+
mode = mode[10:13].lower()
|
| 23 |
+
elif mode.startswith('vi-'):
|
| 24 |
+
mode = mode[3:6]
|
| 25 |
+
return '['+mode+'] '
|
| 26 |
+
return ''
|
| 27 |
+
|
| 28 |
+
def current_line(self) -> int:
|
| 29 |
+
if self.shell.pt_app is not None:
|
| 30 |
+
return self.shell.pt_app.default_buffer.document.cursor_position_row or 0
|
| 31 |
+
return 0
|
| 32 |
+
|
| 33 |
+
def in_prompt_tokens(self):
|
| 34 |
+
return [
|
| 35 |
+
(Token.Prompt, self.vi_mode()),
|
| 36 |
+
(
|
| 37 |
+
Token.Prompt,
|
| 38 |
+
self.shell.prompt_line_number_format.format(
|
| 39 |
+
line=1, rel_line=-self.current_line()
|
| 40 |
+
),
|
| 41 |
+
),
|
| 42 |
+
(Token.Prompt, "In ["),
|
| 43 |
+
(Token.PromptNum, str(self.shell.execution_count)),
|
| 44 |
+
(Token.Prompt, ']: '),
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
def _width(self):
|
| 48 |
+
return fragment_list_width(self.in_prompt_tokens())
|
| 49 |
+
|
| 50 |
+
def continuation_prompt_tokens(self, width=None, *, lineno=None):
|
| 51 |
+
if width is None:
|
| 52 |
+
width = self._width()
|
| 53 |
+
line = lineno + 1 if lineno is not None else 0
|
| 54 |
+
prefix = " " * len(
|
| 55 |
+
self.vi_mode()
|
| 56 |
+
) + self.shell.prompt_line_number_format.format(
|
| 57 |
+
line=line, rel_line=line - self.current_line() - 1
|
| 58 |
+
)
|
| 59 |
+
return [
|
| 60 |
+
(
|
| 61 |
+
Token.Prompt,
|
| 62 |
+
prefix + (" " * (width - len(prefix) - 5)) + "...: ",
|
| 63 |
+
),
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
def rewrite_prompt_tokens(self):
|
| 67 |
+
width = self._width()
|
| 68 |
+
return [
|
| 69 |
+
(Token.Prompt, ('-' * (width - 2)) + '> '),
|
| 70 |
+
]
|
| 71 |
+
|
| 72 |
+
def out_prompt_tokens(self):
|
| 73 |
+
return [
|
| 74 |
+
(Token.OutPrompt, 'Out['),
|
| 75 |
+
(Token.OutPromptNum, str(self.shell.execution_count)),
|
| 76 |
+
(Token.OutPrompt, ']: '),
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
class ClassicPrompts(Prompts):
|
| 80 |
+
def in_prompt_tokens(self):
|
| 81 |
+
return [
|
| 82 |
+
(Token.Prompt, '>>> '),
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
def continuation_prompt_tokens(self, width=None):
|
| 86 |
+
return [
|
| 87 |
+
(Token.Prompt, '... ')
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
def rewrite_prompt_tokens(self):
|
| 91 |
+
return []
|
| 92 |
+
|
| 93 |
+
def out_prompt_tokens(self):
|
| 94 |
+
return []
|
| 95 |
+
|
| 96 |
+
class RichPromptDisplayHook(DisplayHook):
|
| 97 |
+
"""Subclass of base display hook using coloured prompt"""
|
| 98 |
+
def write_output_prompt(self):
|
| 99 |
+
sys.stdout.write(self.shell.separate_out)
|
| 100 |
+
# If we're not displaying a prompt, it effectively ends with a newline,
|
| 101 |
+
# because the output will be left-aligned.
|
| 102 |
+
self.prompt_end_newline = True
|
| 103 |
+
|
| 104 |
+
if self.do_full_cache:
|
| 105 |
+
tokens = self.shell.prompts.out_prompt_tokens()
|
| 106 |
+
prompt_txt = "".join(s for _, s in tokens)
|
| 107 |
+
if prompt_txt and not prompt_txt.endswith("\n"):
|
| 108 |
+
# Ask for a newline before multiline output
|
| 109 |
+
self.prompt_end_newline = False
|
| 110 |
+
|
| 111 |
+
if self.shell.pt_app:
|
| 112 |
+
print_formatted_text(PygmentsTokens(tokens),
|
| 113 |
+
style=self.shell.pt_app.app.style, end='',
|
| 114 |
+
)
|
| 115 |
+
else:
|
| 116 |
+
sys.stdout.write(prompt_txt)
|
| 117 |
+
|
| 118 |
+
def write_format_data(self, format_dict, md_dict=None) -> None:
|
| 119 |
+
assert self.shell is not None
|
| 120 |
+
if self.shell.mime_renderers:
|
| 121 |
+
|
| 122 |
+
for mime, handler in self.shell.mime_renderers.items():
|
| 123 |
+
if mime in format_dict:
|
| 124 |
+
handler(format_dict[mime], None)
|
| 125 |
+
return
|
| 126 |
+
|
| 127 |
+
super().write_format_data(format_dict, md_dict)
|
| 128 |
+
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/ptutils.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""prompt-toolkit utilities
|
| 2 |
+
|
| 3 |
+
Everything in this module is a private API,
|
| 4 |
+
not to be used outside IPython.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
# Copyright (c) IPython Development Team.
|
| 8 |
+
# Distributed under the terms of the Modified BSD License.
|
| 9 |
+
|
| 10 |
+
import unicodedata
|
| 11 |
+
from wcwidth import wcwidth
|
| 12 |
+
|
| 13 |
+
from IPython.core.completer import (
|
| 14 |
+
provisionalcompleter, cursor_to_position,
|
| 15 |
+
_deduplicate_completions)
|
| 16 |
+
from prompt_toolkit.completion import Completer, Completion
|
| 17 |
+
from prompt_toolkit.lexers import Lexer
|
| 18 |
+
from prompt_toolkit.lexers import PygmentsLexer
|
| 19 |
+
from prompt_toolkit.patch_stdout import patch_stdout
|
| 20 |
+
|
| 21 |
+
import pygments.lexers as pygments_lexers
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import traceback
|
| 25 |
+
|
| 26 |
+
_completion_sentinel = object()
|
| 27 |
+
|
| 28 |
+
def _elide_point(string:str, *, min_elide=30)->str:
|
| 29 |
+
"""
|
| 30 |
+
If a string is long enough, and has at least 3 dots,
|
| 31 |
+
replace the middle part with ellipses.
|
| 32 |
+
|
| 33 |
+
If a string naming a file is long enough, and has at least 3 slashes,
|
| 34 |
+
replace the middle part with ellipses.
|
| 35 |
+
|
| 36 |
+
If three consecutive dots, or two consecutive dots are encountered these are
|
| 37 |
+
replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode
|
| 38 |
+
equivalents
|
| 39 |
+
"""
|
| 40 |
+
string = string.replace('...','\N{HORIZONTAL ELLIPSIS}')
|
| 41 |
+
string = string.replace('..','\N{TWO DOT LEADER}')
|
| 42 |
+
if len(string) < min_elide:
|
| 43 |
+
return string
|
| 44 |
+
|
| 45 |
+
object_parts = string.split('.')
|
| 46 |
+
file_parts = string.split(os.sep)
|
| 47 |
+
if file_parts[-1] == '':
|
| 48 |
+
file_parts.pop()
|
| 49 |
+
|
| 50 |
+
if len(object_parts) > 3:
|
| 51 |
+
return "{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}".format(
|
| 52 |
+
object_parts[0],
|
| 53 |
+
object_parts[1][:1],
|
| 54 |
+
object_parts[-2][-1:],
|
| 55 |
+
object_parts[-1],
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
elif len(file_parts) > 3:
|
| 59 |
+
return ("{}" + os.sep + "{}\N{HORIZONTAL ELLIPSIS}{}" + os.sep + "{}").format(
|
| 60 |
+
file_parts[0], file_parts[1][:1], file_parts[-2][-1:], file_parts[-1]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
return string
|
| 64 |
+
|
| 65 |
+
def _elide_typed(string:str, typed:str, *, min_elide:int=30)->str:
|
| 66 |
+
"""
|
| 67 |
+
Elide the middle of a long string if the beginning has already been typed.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
if len(string) < min_elide:
|
| 71 |
+
return string
|
| 72 |
+
cut_how_much = len(typed)-3
|
| 73 |
+
if cut_how_much < 7:
|
| 74 |
+
return string
|
| 75 |
+
if string.startswith(typed) and len(string)> len(typed):
|
| 76 |
+
return f"{string[:3]}\N{HORIZONTAL ELLIPSIS}{string[cut_how_much:]}"
|
| 77 |
+
return string
|
| 78 |
+
|
| 79 |
+
def _elide(string:str, typed:str, min_elide=30)->str:
|
| 80 |
+
return _elide_typed(
|
| 81 |
+
_elide_point(string, min_elide=min_elide),
|
| 82 |
+
typed, min_elide=min_elide)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _adjust_completion_text_based_on_context(text, body, offset):
|
| 87 |
+
if text.endswith('=') and len(body) > offset and body[offset] == '=':
|
| 88 |
+
return text[:-1]
|
| 89 |
+
else:
|
| 90 |
+
return text
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class IPythonPTCompleter(Completer):
|
| 94 |
+
"""Adaptor to provide IPython completions to prompt_toolkit"""
|
| 95 |
+
def __init__(self, ipy_completer=None, shell=None):
|
| 96 |
+
if shell is None and ipy_completer is None:
|
| 97 |
+
raise TypeError("Please pass shell=an InteractiveShell instance.")
|
| 98 |
+
self._ipy_completer = ipy_completer
|
| 99 |
+
self.shell = shell
|
| 100 |
+
|
| 101 |
+
@property
|
| 102 |
+
def ipy_completer(self):
|
| 103 |
+
if self._ipy_completer:
|
| 104 |
+
return self._ipy_completer
|
| 105 |
+
else:
|
| 106 |
+
return self.shell.Completer
|
| 107 |
+
|
| 108 |
+
def get_completions(self, document, complete_event):
|
| 109 |
+
if not document.current_line.strip():
|
| 110 |
+
return
|
| 111 |
+
# Some bits of our completion system may print stuff (e.g. if a module
|
| 112 |
+
# is imported). This context manager ensures that doesn't interfere with
|
| 113 |
+
# the prompt.
|
| 114 |
+
|
| 115 |
+
with patch_stdout(), provisionalcompleter():
|
| 116 |
+
body = document.text
|
| 117 |
+
cursor_row = document.cursor_position_row
|
| 118 |
+
cursor_col = document.cursor_position_col
|
| 119 |
+
cursor_position = document.cursor_position
|
| 120 |
+
offset = cursor_to_position(body, cursor_row, cursor_col)
|
| 121 |
+
try:
|
| 122 |
+
yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)
|
| 123 |
+
except Exception as e:
|
| 124 |
+
try:
|
| 125 |
+
exc_type, exc_value, exc_tb = sys.exc_info()
|
| 126 |
+
traceback.print_exception(exc_type, exc_value, exc_tb)
|
| 127 |
+
except AttributeError:
|
| 128 |
+
print('Unrecoverable Error in completions')
|
| 129 |
+
|
| 130 |
+
@staticmethod
|
| 131 |
+
def _get_completions(body, offset, cursor_position, ipyc):
|
| 132 |
+
"""
|
| 133 |
+
Private equivalent of get_completions() use only for unit_testing.
|
| 134 |
+
"""
|
| 135 |
+
debug = getattr(ipyc, 'debug', False)
|
| 136 |
+
completions = _deduplicate_completions(
|
| 137 |
+
body, ipyc.completions(body, offset))
|
| 138 |
+
for c in completions:
|
| 139 |
+
if not c.text:
|
| 140 |
+
# Guard against completion machinery giving us an empty string.
|
| 141 |
+
continue
|
| 142 |
+
text = unicodedata.normalize('NFC', c.text)
|
| 143 |
+
# When the first character of the completion has a zero length,
|
| 144 |
+
# then it's probably a decomposed unicode character. E.g. caused by
|
| 145 |
+
# the "\dot" completion. Try to compose again with the previous
|
| 146 |
+
# character.
|
| 147 |
+
if wcwidth(text[0]) == 0:
|
| 148 |
+
if cursor_position + c.start > 0:
|
| 149 |
+
char_before = body[c.start - 1]
|
| 150 |
+
fixed_text = unicodedata.normalize(
|
| 151 |
+
'NFC', char_before + text)
|
| 152 |
+
|
| 153 |
+
# Yield the modified completion instead, if this worked.
|
| 154 |
+
if wcwidth(text[0:1]) == 1:
|
| 155 |
+
yield Completion(fixed_text, start_position=c.start - offset - 1)
|
| 156 |
+
continue
|
| 157 |
+
|
| 158 |
+
# TODO: Use Jedi to determine meta_text
|
| 159 |
+
# (Jedi currently has a bug that results in incorrect information.)
|
| 160 |
+
# meta_text = ''
|
| 161 |
+
# yield Completion(m, start_position=start_pos,
|
| 162 |
+
# display_meta=meta_text)
|
| 163 |
+
display_text = c.text
|
| 164 |
+
|
| 165 |
+
adjusted_text = _adjust_completion_text_based_on_context(c.text, body, offset)
|
| 166 |
+
if c.type == 'function':
|
| 167 |
+
yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text+'()', body[c.start:c.end]), display_meta=c.type+c.signature)
|
| 168 |
+
else:
|
| 169 |
+
yield Completion(adjusted_text, start_position=c.start - offset, display=_elide(display_text, body[c.start:c.end]), display_meta=c.type)
|
| 170 |
+
|
| 171 |
+
class IPythonPTLexer(Lexer):
|
| 172 |
+
"""
|
| 173 |
+
Wrapper around PythonLexer and BashLexer.
|
| 174 |
+
"""
|
| 175 |
+
def __init__(self):
|
| 176 |
+
l = pygments_lexers
|
| 177 |
+
self.python_lexer = PygmentsLexer(l.Python3Lexer)
|
| 178 |
+
self.shell_lexer = PygmentsLexer(l.BashLexer)
|
| 179 |
+
|
| 180 |
+
self.magic_lexers = {
|
| 181 |
+
'HTML': PygmentsLexer(l.HtmlLexer),
|
| 182 |
+
'html': PygmentsLexer(l.HtmlLexer),
|
| 183 |
+
'javascript': PygmentsLexer(l.JavascriptLexer),
|
| 184 |
+
'js': PygmentsLexer(l.JavascriptLexer),
|
| 185 |
+
'perl': PygmentsLexer(l.PerlLexer),
|
| 186 |
+
'ruby': PygmentsLexer(l.RubyLexer),
|
| 187 |
+
'latex': PygmentsLexer(l.TexLexer),
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
def lex_document(self, document):
|
| 191 |
+
text = document.text.lstrip()
|
| 192 |
+
|
| 193 |
+
lexer = self.python_lexer
|
| 194 |
+
|
| 195 |
+
if text.startswith('!') or text.startswith('%%bash'):
|
| 196 |
+
lexer = self.shell_lexer
|
| 197 |
+
|
| 198 |
+
elif text.startswith('%%'):
|
| 199 |
+
for magic, l in self.magic_lexers.items():
|
| 200 |
+
if text.startswith('%%' + magic):
|
| 201 |
+
lexer = l
|
| 202 |
+
break
|
| 203 |
+
|
| 204 |
+
return lexer.lex_document(document)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/__init__.py
ADDED
|
File without changes
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/fake_llm.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
|
| 3 |
+
try:
|
| 4 |
+
from jupyter_ai_magics import BaseProvider
|
| 5 |
+
from langchain_community.llms import FakeListLLM
|
| 6 |
+
except ImportError:
|
| 7 |
+
|
| 8 |
+
class BaseProvider:
|
| 9 |
+
pass
|
| 10 |
+
|
| 11 |
+
class FakeListLLM:
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
FIBONACCI = """\
|
| 16 |
+
def fib(n):
|
| 17 |
+
if n < 2: return n
|
| 18 |
+
return fib(n - 1) + fib(n - 2)
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FibonacciCompletionProvider(BaseProvider, FakeListLLM): # type: ignore[misc, valid-type]
|
| 23 |
+
|
| 24 |
+
id = "my_provider"
|
| 25 |
+
name = "My Provider"
|
| 26 |
+
model_id_key = "model"
|
| 27 |
+
models = ["model_a"]
|
| 28 |
+
|
| 29 |
+
def __init__(self, **kwargs):
|
| 30 |
+
kwargs["responses"] = ["This fake response will not be used for completion"]
|
| 31 |
+
kwargs["model_id"] = "model_a"
|
| 32 |
+
super().__init__(**kwargs)
|
| 33 |
+
|
| 34 |
+
async def generate_inline_completions(self, request):
|
| 35 |
+
raise ValueError("IPython only supports streaming models.")
|
| 36 |
+
|
| 37 |
+
async def stream_inline_completions(self, request):
|
| 38 |
+
from jupyter_ai.completions.models import (
|
| 39 |
+
InlineCompletionList,
|
| 40 |
+
InlineCompletionReply,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
assert request.number > 0
|
| 44 |
+
token = f"t{request.number}s0"
|
| 45 |
+
last_line = request.prefix.rstrip("\n").splitlines()[-1]
|
| 46 |
+
|
| 47 |
+
if not FIBONACCI.startswith(last_line):
|
| 48 |
+
return
|
| 49 |
+
|
| 50 |
+
yield InlineCompletionReply(
|
| 51 |
+
list=InlineCompletionList(
|
| 52 |
+
items=[
|
| 53 |
+
{"insertText": "", "isIncomplete": True, "token": token},
|
| 54 |
+
]
|
| 55 |
+
),
|
| 56 |
+
reply_to=request.number,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
async for reply in self._stream(
|
| 60 |
+
FIBONACCI[len(last_line) :],
|
| 61 |
+
request.number,
|
| 62 |
+
token,
|
| 63 |
+
):
|
| 64 |
+
yield reply
|
| 65 |
+
|
| 66 |
+
async def _stream(self, sentence, request_number, token, start_with=""):
|
| 67 |
+
from jupyter_ai.completions.models import InlineCompletionStreamChunk
|
| 68 |
+
|
| 69 |
+
suggestion = start_with
|
| 70 |
+
|
| 71 |
+
for fragment in sentence.split(" "):
|
| 72 |
+
await asyncio.sleep(0.05)
|
| 73 |
+
if suggestion:
|
| 74 |
+
suggestion += " "
|
| 75 |
+
suggestion += fragment
|
| 76 |
+
yield InlineCompletionStreamChunk(
|
| 77 |
+
type="stream",
|
| 78 |
+
response={"insertText": suggestion, "token": token},
|
| 79 |
+
reply_to=request_number,
|
| 80 |
+
done=False,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# finally, send a message confirming that we are done
|
| 84 |
+
yield InlineCompletionStreamChunk(
|
| 85 |
+
type="stream",
|
| 86 |
+
response={"insertText": suggestion, "token": token},
|
| 87 |
+
reply_to=request_number,
|
| 88 |
+
done=True,
|
| 89 |
+
)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_debug_magic.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test embedding of IPython"""
|
| 2 |
+
|
| 3 |
+
#-----------------------------------------------------------------------------
|
| 4 |
+
# Copyright (C) 2013 The IPython Development Team
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
#-----------------------------------------------------------------------------
|
| 9 |
+
|
| 10 |
+
#-----------------------------------------------------------------------------
|
| 11 |
+
# Imports
|
| 12 |
+
#-----------------------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
from IPython.testing.decorators import skip_win32
|
| 17 |
+
from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
|
| 18 |
+
|
| 19 |
+
#-----------------------------------------------------------------------------
|
| 20 |
+
# Tests
|
| 21 |
+
#-----------------------------------------------------------------------------
|
| 22 |
+
|
| 23 |
+
@skip_win32
|
| 24 |
+
def test_debug_magic_passes_through_generators():
|
| 25 |
+
"""
|
| 26 |
+
This test that we can correctly pass through frames of a generator post-mortem.
|
| 27 |
+
"""
|
| 28 |
+
import pexpect
|
| 29 |
+
import re
|
| 30 |
+
in_prompt = re.compile(br'In ?\[\d+\]:')
|
| 31 |
+
ipdb_prompt = 'ipdb>'
|
| 32 |
+
env = os.environ.copy()
|
| 33 |
+
child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor', '--simple-prompt'],
|
| 34 |
+
env=env)
|
| 35 |
+
child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
|
| 36 |
+
|
| 37 |
+
child.expect(in_prompt)
|
| 38 |
+
|
| 39 |
+
child.timeout = 2 * IPYTHON_TESTING_TIMEOUT_SCALE
|
| 40 |
+
|
| 41 |
+
child.sendline("def f(x):")
|
| 42 |
+
child.sendline(" raise Exception")
|
| 43 |
+
child.sendline("")
|
| 44 |
+
|
| 45 |
+
child.expect(in_prompt)
|
| 46 |
+
child.sendline("gen = (f(x) for x in [0])")
|
| 47 |
+
child.sendline("")
|
| 48 |
+
|
| 49 |
+
child.expect(in_prompt)
|
| 50 |
+
child.sendline("for x in gen:")
|
| 51 |
+
child.sendline(" pass")
|
| 52 |
+
child.sendline("")
|
| 53 |
+
|
| 54 |
+
child.timeout = 10 * IPYTHON_TESTING_TIMEOUT_SCALE
|
| 55 |
+
|
| 56 |
+
child.expect('Exception:')
|
| 57 |
+
|
| 58 |
+
child.expect(in_prompt)
|
| 59 |
+
child.sendline(r'%debug')
|
| 60 |
+
child.expect('----> 2 raise Exception')
|
| 61 |
+
|
| 62 |
+
child.expect(ipdb_prompt)
|
| 63 |
+
child.sendline('u')
|
| 64 |
+
child.expect_exact(r'----> 1 gen = (f(x) for x in [0])')
|
| 65 |
+
|
| 66 |
+
child.expect(ipdb_prompt)
|
| 67 |
+
child.sendline('u')
|
| 68 |
+
child.expect_exact('----> 1 for x in gen:')
|
| 69 |
+
|
| 70 |
+
child.expect(ipdb_prompt)
|
| 71 |
+
child.sendline("u")
|
| 72 |
+
child.expect_exact(
|
| 73 |
+
"*** all frames above hidden, use `skip_hidden False` to get get into those."
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
child.expect(ipdb_prompt)
|
| 77 |
+
child.sendline('exit')
|
| 78 |
+
|
| 79 |
+
child.expect(in_prompt)
|
| 80 |
+
child.sendline('exit')
|
| 81 |
+
|
| 82 |
+
child.close()
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_embed.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test embedding of IPython"""
|
| 2 |
+
|
| 3 |
+
#-----------------------------------------------------------------------------
|
| 4 |
+
# Copyright (C) 2013 The IPython Development Team
|
| 5 |
+
#
|
| 6 |
+
# Distributed under the terms of the BSD License. The full license is in
|
| 7 |
+
# the file COPYING, distributed as part of this software.
|
| 8 |
+
#-----------------------------------------------------------------------------
|
| 9 |
+
|
| 10 |
+
#-----------------------------------------------------------------------------
|
| 11 |
+
# Imports
|
| 12 |
+
#-----------------------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import subprocess
|
| 16 |
+
import sys
|
| 17 |
+
|
| 18 |
+
from IPython.utils.tempdir import NamedFileInTemporaryDirectory
|
| 19 |
+
from IPython.testing.decorators import skip_win32
|
| 20 |
+
from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
|
| 21 |
+
|
| 22 |
+
#-----------------------------------------------------------------------------
|
| 23 |
+
# Tests
|
| 24 |
+
#-----------------------------------------------------------------------------
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_sample_embed = b"""
|
| 28 |
+
import IPython
|
| 29 |
+
|
| 30 |
+
a = 3
|
| 31 |
+
b = 14
|
| 32 |
+
print(a, '.', b)
|
| 33 |
+
|
| 34 |
+
IPython.embed()
|
| 35 |
+
|
| 36 |
+
print('bye!')
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
_exit = b"exit\r"
|
| 40 |
+
|
| 41 |
+
def test_ipython_embed():
|
| 42 |
+
"""test that `IPython.embed()` works"""
|
| 43 |
+
with NamedFileInTemporaryDirectory('file_with_embed.py') as f:
|
| 44 |
+
f.write(_sample_embed)
|
| 45 |
+
f.flush()
|
| 46 |
+
f.close() # otherwise msft won't be able to read the file
|
| 47 |
+
|
| 48 |
+
# run `python file_with_embed.py`
|
| 49 |
+
cmd = [sys.executable, f.name]
|
| 50 |
+
env = os.environ.copy()
|
| 51 |
+
env['IPY_TEST_SIMPLE_PROMPT'] = '1'
|
| 52 |
+
|
| 53 |
+
p = subprocess.Popen(cmd, env=env, stdin=subprocess.PIPE,
|
| 54 |
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 55 |
+
out, err = p.communicate(_exit)
|
| 56 |
+
std = out.decode('UTF-8')
|
| 57 |
+
|
| 58 |
+
assert p.returncode == 0
|
| 59 |
+
assert "3 . 14" in std
|
| 60 |
+
if os.name != "nt":
|
| 61 |
+
# TODO: Fix up our different stdout references, see issue gh-14
|
| 62 |
+
assert "IPython" in std
|
| 63 |
+
assert "bye!" in std
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@skip_win32
|
| 67 |
+
def test_nest_embed():
|
| 68 |
+
"""test that `IPython.embed()` is nestable"""
|
| 69 |
+
import pexpect
|
| 70 |
+
ipy_prompt = r']:' #ansi color codes give problems matching beyond this
|
| 71 |
+
env = os.environ.copy()
|
| 72 |
+
env['IPY_TEST_SIMPLE_PROMPT'] = '1'
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
child = pexpect.spawn(sys.executable, ['-m', 'IPython', '--colors=nocolor'],
|
| 76 |
+
env=env)
|
| 77 |
+
child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
|
| 78 |
+
child.expect(ipy_prompt)
|
| 79 |
+
child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE
|
| 80 |
+
child.sendline("import IPython")
|
| 81 |
+
child.expect(ipy_prompt)
|
| 82 |
+
child.sendline("ip0 = get_ipython()")
|
| 83 |
+
#enter first nested embed
|
| 84 |
+
child.sendline("IPython.embed()")
|
| 85 |
+
#skip the banner until we get to a prompt
|
| 86 |
+
try:
|
| 87 |
+
prompted = -1
|
| 88 |
+
while prompted != 0:
|
| 89 |
+
prompted = child.expect([ipy_prompt, '\r\n'])
|
| 90 |
+
except pexpect.TIMEOUT as e:
|
| 91 |
+
print(e)
|
| 92 |
+
#child.interact()
|
| 93 |
+
child.sendline("embed1 = get_ipython()")
|
| 94 |
+
child.expect(ipy_prompt)
|
| 95 |
+
child.sendline("print('true' if embed1 is not ip0 else 'false')")
|
| 96 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 97 |
+
child.expect(ipy_prompt)
|
| 98 |
+
child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
|
| 99 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 100 |
+
child.expect(ipy_prompt)
|
| 101 |
+
#enter second nested embed
|
| 102 |
+
child.sendline("IPython.embed()")
|
| 103 |
+
#skip the banner until we get to a prompt
|
| 104 |
+
try:
|
| 105 |
+
prompted = -1
|
| 106 |
+
while prompted != 0:
|
| 107 |
+
prompted = child.expect([ipy_prompt, '\r\n'])
|
| 108 |
+
except pexpect.TIMEOUT as e:
|
| 109 |
+
print(e)
|
| 110 |
+
#child.interact()
|
| 111 |
+
child.sendline("embed2 = get_ipython()")
|
| 112 |
+
child.expect(ipy_prompt)
|
| 113 |
+
child.sendline("print('true' if embed2 is not embed1 else 'false')")
|
| 114 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 115 |
+
child.expect(ipy_prompt)
|
| 116 |
+
child.sendline("print('true' if embed2 is IPython.get_ipython() else 'false')")
|
| 117 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 118 |
+
child.expect(ipy_prompt)
|
| 119 |
+
child.sendline('exit')
|
| 120 |
+
#back at first embed
|
| 121 |
+
child.expect(ipy_prompt)
|
| 122 |
+
child.sendline("print('true' if get_ipython() is embed1 else 'false')")
|
| 123 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 124 |
+
child.expect(ipy_prompt)
|
| 125 |
+
child.sendline("print('true' if IPython.get_ipython() is embed1 else 'false')")
|
| 126 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 127 |
+
child.expect(ipy_prompt)
|
| 128 |
+
child.sendline('exit')
|
| 129 |
+
#back at launching scope
|
| 130 |
+
child.expect(ipy_prompt)
|
| 131 |
+
child.sendline("print('true' if get_ipython() is ip0 else 'false')")
|
| 132 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 133 |
+
child.expect(ipy_prompt)
|
| 134 |
+
child.sendline("print('true' if IPython.get_ipython() is ip0 else 'false')")
|
| 135 |
+
assert(child.expect(['true\r\n', 'false\r\n']) == 0)
|
| 136 |
+
child.expect(ipy_prompt)
|
| 137 |
+
child.sendline('exit')
|
| 138 |
+
child.close()
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_help.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test help output of various IPython entry points"""
|
| 2 |
+
|
| 3 |
+
# Copyright (c) IPython Development Team.
|
| 4 |
+
# Distributed under the terms of the Modified BSD License.
|
| 5 |
+
|
| 6 |
+
import pytest
|
| 7 |
+
import IPython.testing.tools as tt
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def test_ipython_help():
|
| 11 |
+
tt.help_all_output_test()
|
| 12 |
+
|
| 13 |
+
def test_profile_help():
|
| 14 |
+
tt.help_all_output_test("profile")
|
| 15 |
+
|
| 16 |
+
def test_profile_list_help():
|
| 17 |
+
tt.help_all_output_test("profile list")
|
| 18 |
+
|
| 19 |
+
def test_profile_create_help():
|
| 20 |
+
tt.help_all_output_test("profile create")
|
| 21 |
+
|
| 22 |
+
def test_locate_help():
|
| 23 |
+
tt.help_all_output_test("locate")
|
| 24 |
+
|
| 25 |
+
def test_locate_profile_help():
|
| 26 |
+
tt.help_all_output_test("locate profile")
|
| 27 |
+
|
| 28 |
+
def test_trust_help():
|
| 29 |
+
pytest.importorskip("nbformat")
|
| 30 |
+
tt.help_all_output_test("trust")
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_interactivshell.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Tests for the TerminalInteractiveShell and related pieces."""
|
| 3 |
+
# Copyright (c) IPython Development Team.
|
| 4 |
+
# Distributed under the terms of the Modified BSD License.
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import unittest
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
from IPython.testing import tools as tt
|
| 14 |
+
|
| 15 |
+
from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context
|
| 16 |
+
from IPython.terminal.shortcuts.auto_suggest import NavigableAutoSuggestFromHistory
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class TestAutoSuggest(unittest.TestCase):
|
| 20 |
+
def test_changing_provider(self):
|
| 21 |
+
ip = get_ipython()
|
| 22 |
+
ip.autosuggestions_provider = None
|
| 23 |
+
self.assertEqual(ip.auto_suggest, None)
|
| 24 |
+
ip.autosuggestions_provider = "AutoSuggestFromHistory"
|
| 25 |
+
self.assertIsInstance(ip.auto_suggest, AutoSuggestFromHistory)
|
| 26 |
+
ip.autosuggestions_provider = "NavigableAutoSuggestFromHistory"
|
| 27 |
+
self.assertIsInstance(ip.auto_suggest, NavigableAutoSuggestFromHistory)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestElide(unittest.TestCase):
|
| 31 |
+
def test_elide(self):
|
| 32 |
+
_elide("concatenate((a1, a2, ...), axis", "") # do not raise
|
| 33 |
+
_elide("concatenate((a1, a2, ..), . axis", "") # do not raise
|
| 34 |
+
self.assertEqual(
|
| 35 |
+
_elide("aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh", ""),
|
| 36 |
+
"aaaa.b…g.hhhhhh",
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
test_string = os.sep.join(["", 10 * "a", 10 * "b", 10 * "c", ""])
|
| 40 |
+
expect_string = (
|
| 41 |
+
os.sep + "a" + "\N{HORIZONTAL ELLIPSIS}" + "b" + os.sep + 10 * "c"
|
| 42 |
+
)
|
| 43 |
+
self.assertEqual(_elide(test_string, ""), expect_string)
|
| 44 |
+
|
| 45 |
+
def test_elide_typed_normal(self):
|
| 46 |
+
self.assertEqual(
|
| 47 |
+
_elide(
|
| 48 |
+
"the quick brown fox jumped over the lazy dog",
|
| 49 |
+
"the quick brown fox",
|
| 50 |
+
min_elide=10,
|
| 51 |
+
),
|
| 52 |
+
"the…fox jumped over the lazy dog",
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def test_elide_typed_short_match(self):
|
| 56 |
+
"""
|
| 57 |
+
if the match is too short we don't elide.
|
| 58 |
+
avoid the "the...the"
|
| 59 |
+
"""
|
| 60 |
+
self.assertEqual(
|
| 61 |
+
_elide("the quick brown fox jumped over the lazy dog", "the", min_elide=10),
|
| 62 |
+
"the quick brown fox jumped over the lazy dog",
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def test_elide_typed_no_match(self):
|
| 66 |
+
"""
|
| 67 |
+
if the match is too short we don't elide.
|
| 68 |
+
avoid the "the...the"
|
| 69 |
+
"""
|
| 70 |
+
# here we typed red instead of brown
|
| 71 |
+
self.assertEqual(
|
| 72 |
+
_elide(
|
| 73 |
+
"the quick brown fox jumped over the lazy dog",
|
| 74 |
+
"the quick red fox",
|
| 75 |
+
min_elide=10,
|
| 76 |
+
),
|
| 77 |
+
"the quick brown fox jumped over the lazy dog",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class TestContextAwareCompletion(unittest.TestCase):
|
| 82 |
+
def test_adjust_completion_text_based_on_context(self):
|
| 83 |
+
# Adjusted case
|
| 84 |
+
self.assertEqual(
|
| 85 |
+
_adjust_completion_text_based_on_context("arg1=", "func1(a=)", 7), "arg1"
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Untouched cases
|
| 89 |
+
self.assertEqual(
|
| 90 |
+
_adjust_completion_text_based_on_context("arg1=", "func1(a)", 7), "arg1="
|
| 91 |
+
)
|
| 92 |
+
self.assertEqual(
|
| 93 |
+
_adjust_completion_text_based_on_context("arg1=", "func1(a", 7), "arg1="
|
| 94 |
+
)
|
| 95 |
+
self.assertEqual(
|
| 96 |
+
_adjust_completion_text_based_on_context("%magic", "func1(a=)", 7), "%magic"
|
| 97 |
+
)
|
| 98 |
+
self.assertEqual(
|
| 99 |
+
_adjust_completion_text_based_on_context("func2", "func1(a=)", 7), "func2"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# Decorator for interaction loop tests -----------------------------------------
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class mock_input_helper(object):
|
| 107 |
+
"""Machinery for tests of the main interact loop.
|
| 108 |
+
|
| 109 |
+
Used by the mock_input decorator.
|
| 110 |
+
"""
|
| 111 |
+
def __init__(self, testgen):
|
| 112 |
+
self.testgen = testgen
|
| 113 |
+
self.exception = None
|
| 114 |
+
self.ip = get_ipython()
|
| 115 |
+
|
| 116 |
+
def __enter__(self):
|
| 117 |
+
self.orig_prompt_for_code = self.ip.prompt_for_code
|
| 118 |
+
self.ip.prompt_for_code = self.fake_input
|
| 119 |
+
return self
|
| 120 |
+
|
| 121 |
+
def __exit__(self, etype, value, tb):
|
| 122 |
+
self.ip.prompt_for_code = self.orig_prompt_for_code
|
| 123 |
+
|
| 124 |
+
def fake_input(self):
|
| 125 |
+
try:
|
| 126 |
+
return next(self.testgen)
|
| 127 |
+
except StopIteration:
|
| 128 |
+
self.ip.keep_running = False
|
| 129 |
+
return u''
|
| 130 |
+
except:
|
| 131 |
+
self.exception = sys.exc_info()
|
| 132 |
+
self.ip.keep_running = False
|
| 133 |
+
return u''
|
| 134 |
+
|
| 135 |
+
def mock_input(testfunc):
|
| 136 |
+
"""Decorator for tests of the main interact loop.
|
| 137 |
+
|
| 138 |
+
Write the test as a generator, yield-ing the input strings, which IPython
|
| 139 |
+
will see as if they were typed in at the prompt.
|
| 140 |
+
"""
|
| 141 |
+
def test_method(self):
|
| 142 |
+
testgen = testfunc(self)
|
| 143 |
+
with mock_input_helper(testgen) as mih:
|
| 144 |
+
mih.ip.interact()
|
| 145 |
+
|
| 146 |
+
if mih.exception is not None:
|
| 147 |
+
# Re-raise captured exception
|
| 148 |
+
etype, value, tb = mih.exception
|
| 149 |
+
import traceback
|
| 150 |
+
traceback.print_tb(tb, file=sys.stdout)
|
| 151 |
+
del tb # Avoid reference loop
|
| 152 |
+
raise value
|
| 153 |
+
|
| 154 |
+
return test_method
|
| 155 |
+
|
| 156 |
+
# Test classes -----------------------------------------------------------------
|
| 157 |
+
|
| 158 |
+
class InteractiveShellTestCase(unittest.TestCase):
|
| 159 |
+
def rl_hist_entries(self, rl, n):
|
| 160 |
+
"""Get last n readline history entries as a list"""
|
| 161 |
+
return [rl.get_history_item(rl.get_current_history_length() - x)
|
| 162 |
+
for x in range(n - 1, -1, -1)]
|
| 163 |
+
|
| 164 |
+
@mock_input
|
| 165 |
+
def test_inputtransformer_syntaxerror(self):
|
| 166 |
+
ip = get_ipython()
|
| 167 |
+
ip.input_transformers_post.append(syntax_error_transformer)
|
| 168 |
+
|
| 169 |
+
try:
|
| 170 |
+
#raise Exception
|
| 171 |
+
with tt.AssertPrints('4', suppress=False):
|
| 172 |
+
yield u'print(2*2)'
|
| 173 |
+
|
| 174 |
+
with tt.AssertPrints('SyntaxError: input contains', suppress=False):
|
| 175 |
+
yield u'print(2345) # syntaxerror'
|
| 176 |
+
|
| 177 |
+
with tt.AssertPrints('16', suppress=False):
|
| 178 |
+
yield u'print(4*4)'
|
| 179 |
+
|
| 180 |
+
finally:
|
| 181 |
+
ip.input_transformers_post.remove(syntax_error_transformer)
|
| 182 |
+
|
| 183 |
+
def test_repl_not_plain_text(self):
|
| 184 |
+
ip = get_ipython()
|
| 185 |
+
formatter = ip.display_formatter
|
| 186 |
+
assert formatter.active_types == ['text/plain']
|
| 187 |
+
|
| 188 |
+
# terminal may have arbitrary mimetype handler to open external viewer
|
| 189 |
+
# or inline images.
|
| 190 |
+
assert formatter.ipython_display_formatter.enabled
|
| 191 |
+
|
| 192 |
+
class Test(object):
|
| 193 |
+
def __repr__(self):
|
| 194 |
+
return "<Test %i>" % id(self)
|
| 195 |
+
|
| 196 |
+
def _repr_html_(self):
|
| 197 |
+
return '<html>'
|
| 198 |
+
|
| 199 |
+
# verify that HTML repr isn't computed
|
| 200 |
+
obj = Test()
|
| 201 |
+
data, _ = formatter.format(obj)
|
| 202 |
+
self.assertEqual(data, {'text/plain': repr(obj)})
|
| 203 |
+
|
| 204 |
+
class Test2(Test):
|
| 205 |
+
def _ipython_display_(self):
|
| 206 |
+
from IPython.display import display, HTML
|
| 207 |
+
|
| 208 |
+
display(HTML("<custom>"))
|
| 209 |
+
|
| 210 |
+
# verify that mimehandlers are called
|
| 211 |
+
called = False
|
| 212 |
+
|
| 213 |
+
def handler(data, metadata):
|
| 214 |
+
print("Handler called")
|
| 215 |
+
nonlocal called
|
| 216 |
+
called = True
|
| 217 |
+
|
| 218 |
+
ip.display_formatter.active_types.append("text/html")
|
| 219 |
+
ip.display_formatter.formatters["text/html"].enabled = True
|
| 220 |
+
ip.mime_renderers["text/html"] = handler
|
| 221 |
+
try:
|
| 222 |
+
obj = Test()
|
| 223 |
+
display(obj)
|
| 224 |
+
finally:
|
| 225 |
+
ip.display_formatter.formatters["text/html"].enabled = False
|
| 226 |
+
del ip.mime_renderers["text/html"]
|
| 227 |
+
|
| 228 |
+
assert called == True
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def syntax_error_transformer(lines):
|
| 232 |
+
"""Transformer that throws SyntaxError if 'syntaxerror' is in the code."""
|
| 233 |
+
for line in lines:
|
| 234 |
+
pos = line.find('syntaxerror')
|
| 235 |
+
if pos >= 0:
|
| 236 |
+
e = SyntaxError('input contains "syntaxerror"')
|
| 237 |
+
e.text = line
|
| 238 |
+
e.offset = pos + 1
|
| 239 |
+
raise e
|
| 240 |
+
return lines
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class TerminalMagicsTestCase(unittest.TestCase):
|
| 244 |
+
def test_paste_magics_blankline(self):
|
| 245 |
+
"""Test that code with a blank line doesn't get split (gh-3246)."""
|
| 246 |
+
ip = get_ipython()
|
| 247 |
+
s = ('def pasted_func(a):\n'
|
| 248 |
+
' b = a+1\n'
|
| 249 |
+
'\n'
|
| 250 |
+
' return b')
|
| 251 |
+
|
| 252 |
+
tm = ip.magics_manager.registry['TerminalMagics']
|
| 253 |
+
tm.store_or_execute(s, name=None)
|
| 254 |
+
|
| 255 |
+
self.assertEqual(ip.user_ns['pasted_func'](54), 55)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_pt_inputhooks.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import importlib
|
| 3 |
+
|
| 4 |
+
import pytest
|
| 5 |
+
|
| 6 |
+
from IPython.terminal.pt_inputhooks import set_qt_api, get_inputhook_name_and_func
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
guis_avail = []
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _get_qt_vers():
|
| 13 |
+
"""If any version of Qt is available, this will populate `guis_avail` with 'qt' and 'qtx'. Due
|
| 14 |
+
to the import mechanism, we can't import multiple versions of Qt in one session."""
|
| 15 |
+
for gui in ["qt", "qt6", "qt5"]:
|
| 16 |
+
print(f"Trying {gui}")
|
| 17 |
+
try:
|
| 18 |
+
set_qt_api(gui)
|
| 19 |
+
importlib.import_module("IPython.terminal.pt_inputhooks.qt")
|
| 20 |
+
guis_avail.append(gui)
|
| 21 |
+
if "QT_API" in os.environ.keys():
|
| 22 |
+
del os.environ["QT_API"]
|
| 23 |
+
except ImportError:
|
| 24 |
+
pass # that version of Qt isn't available.
|
| 25 |
+
except RuntimeError:
|
| 26 |
+
pass # the version of IPython doesn't know what to do with this Qt version.
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_get_qt_vers()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@pytest.mark.skipif(
|
| 33 |
+
len(guis_avail) == 0, reason="No viable version of PyQt or PySide installed."
|
| 34 |
+
)
|
| 35 |
+
def test_inputhook_qt():
|
| 36 |
+
# Choose the "best" Qt version.
|
| 37 |
+
gui_ret, _ = get_inputhook_name_and_func("qt")
|
| 38 |
+
|
| 39 |
+
assert gui_ret != "qt" # you get back the specific version that was loaded.
|
| 40 |
+
assert gui_ret in guis_avail
|
| 41 |
+
|
| 42 |
+
if len(guis_avail) > 2:
|
| 43 |
+
# ...and now we're stuck with this version of Qt for good; can't switch.
|
| 44 |
+
for not_gui in ["qt6", "qt5"]:
|
| 45 |
+
if not_gui != gui_ret:
|
| 46 |
+
break
|
| 47 |
+
# Try to import the other gui; it won't work.
|
| 48 |
+
gui_ret2, _ = get_inputhook_name_and_func(not_gui)
|
| 49 |
+
assert gui_ret2 == gui_ret
|
| 50 |
+
assert gui_ret2 != not_gui
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/terminal/tests/test_shortcuts.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
from IPython.terminal.shortcuts.auto_suggest import (
|
| 3 |
+
accept,
|
| 4 |
+
accept_or_jump_to_end,
|
| 5 |
+
accept_token,
|
| 6 |
+
accept_character,
|
| 7 |
+
accept_word,
|
| 8 |
+
accept_and_keep_cursor,
|
| 9 |
+
discard,
|
| 10 |
+
llm_autosuggestion,
|
| 11 |
+
NavigableAutoSuggestFromHistory,
|
| 12 |
+
swap_autosuggestion_up,
|
| 13 |
+
swap_autosuggestion_down,
|
| 14 |
+
)
|
| 15 |
+
from IPython.terminal.shortcuts.auto_match import skip_over
|
| 16 |
+
from IPython.terminal.shortcuts import create_ipython_shortcuts, reset_search_buffer
|
| 17 |
+
from IPython.testing import decorators as dec
|
| 18 |
+
|
| 19 |
+
from prompt_toolkit.history import InMemoryHistory
|
| 20 |
+
from prompt_toolkit.buffer import Buffer
|
| 21 |
+
from prompt_toolkit.document import Document
|
| 22 |
+
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
|
| 23 |
+
from prompt_toolkit.enums import DEFAULT_BUFFER
|
| 24 |
+
|
| 25 |
+
from unittest.mock import patch, Mock
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_deprected():
|
| 29 |
+
import IPython.terminal.shortcuts.auto_suggest as iptsa
|
| 30 |
+
|
| 31 |
+
with pytest.warns(DeprecationWarning, match=r"8\.12.+accept_or_jump_to_end"):
|
| 32 |
+
iptsa.accept_in_vi_insert_mode
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def make_event(text, cursor, suggestion):
|
| 36 |
+
event = Mock()
|
| 37 |
+
event.current_buffer = Mock()
|
| 38 |
+
event.current_buffer.suggestion = Mock()
|
| 39 |
+
event.current_buffer.text = text
|
| 40 |
+
event.current_buffer.cursor_position = cursor
|
| 41 |
+
event.current_buffer.suggestion.text = suggestion
|
| 42 |
+
event.current_buffer.document = Document(text=text, cursor_position=cursor)
|
| 43 |
+
return event
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
from .fake_llm import FIBONACCI
|
| 48 |
+
except ImportError:
|
| 49 |
+
FIBONACCI = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dec.skip_without("jupyter_ai")
|
| 53 |
+
@pytest.mark.asyncio
|
| 54 |
+
async def test_llm_autosuggestion():
|
| 55 |
+
provider = NavigableAutoSuggestFromHistory()
|
| 56 |
+
ip = get_ipython()
|
| 57 |
+
ip.auto_suggest = provider
|
| 58 |
+
ip.llm_provider_class = "IPython.terminal.tests.fake_llm.FibonacciCompletionProvider"
|
| 59 |
+
text = "def fib"
|
| 60 |
+
event = make_event(text, len(text), "")
|
| 61 |
+
event.current_buffer.history.shell.history_manager.get_range = Mock(return_value=[])
|
| 62 |
+
await llm_autosuggestion(event)
|
| 63 |
+
assert event.current_buffer.suggestion.text == FIBONACCI[len(text) :]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize(
|
| 67 |
+
"text, suggestion, expected",
|
| 68 |
+
[
|
| 69 |
+
("", "def out(tag: str, n=50):", "def out(tag: str, n=50):"),
|
| 70 |
+
("def ", "out(tag: str, n=50):", "out(tag: str, n=50):"),
|
| 71 |
+
],
|
| 72 |
+
)
|
| 73 |
+
def test_accept(text, suggestion, expected):
|
| 74 |
+
event = make_event(text, len(text), suggestion)
|
| 75 |
+
buffer = event.current_buffer
|
| 76 |
+
buffer.insert_text = Mock()
|
| 77 |
+
accept(event)
|
| 78 |
+
assert buffer.insert_text.called
|
| 79 |
+
assert buffer.insert_text.call_args[0] == (expected,)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@pytest.mark.parametrize(
|
| 83 |
+
"text, suggestion",
|
| 84 |
+
[
|
| 85 |
+
("", "def out(tag: str, n=50):"),
|
| 86 |
+
("def ", "out(tag: str, n=50):"),
|
| 87 |
+
],
|
| 88 |
+
)
|
| 89 |
+
def test_discard(text, suggestion):
|
| 90 |
+
event = make_event(text, len(text), suggestion)
|
| 91 |
+
buffer = event.current_buffer
|
| 92 |
+
buffer.insert_text = Mock()
|
| 93 |
+
discard(event)
|
| 94 |
+
assert not buffer.insert_text.called
|
| 95 |
+
assert buffer.suggestion is None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@pytest.mark.parametrize(
|
| 99 |
+
"text, cursor, suggestion, called",
|
| 100 |
+
[
|
| 101 |
+
("123456", 6, "123456789", True),
|
| 102 |
+
("123456", 3, "123456789", False),
|
| 103 |
+
("123456 \n789", 6, "123456789", True),
|
| 104 |
+
],
|
| 105 |
+
)
|
| 106 |
+
def test_autosuggest_at_EOL(text, cursor, suggestion, called):
|
| 107 |
+
"""
|
| 108 |
+
test that autosuggest is only applied at end of line.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
event = make_event(text, cursor, suggestion)
|
| 112 |
+
event.current_buffer.insert_text = Mock()
|
| 113 |
+
accept_or_jump_to_end(event)
|
| 114 |
+
if called:
|
| 115 |
+
event.current_buffer.insert_text.assert_called()
|
| 116 |
+
else:
|
| 117 |
+
event.current_buffer.insert_text.assert_not_called()
|
| 118 |
+
# event.current_buffer.document.get_end_of_line_position.assert_called()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
@pytest.mark.parametrize(
|
| 122 |
+
"text, suggestion, expected",
|
| 123 |
+
[
|
| 124 |
+
("", "def out(tag: str, n=50):", "def "),
|
| 125 |
+
("d", "ef out(tag: str, n=50):", "ef "),
|
| 126 |
+
("de ", "f out(tag: str, n=50):", "f "),
|
| 127 |
+
("def", " out(tag: str, n=50):", " "),
|
| 128 |
+
("def ", "out(tag: str, n=50):", "out("),
|
| 129 |
+
("def o", "ut(tag: str, n=50):", "ut("),
|
| 130 |
+
("def ou", "t(tag: str, n=50):", "t("),
|
| 131 |
+
("def out", "(tag: str, n=50):", "("),
|
| 132 |
+
("def out(", "tag: str, n=50):", "tag: "),
|
| 133 |
+
("def out(t", "ag: str, n=50):", "ag: "),
|
| 134 |
+
("def out(ta", "g: str, n=50):", "g: "),
|
| 135 |
+
("def out(tag", ": str, n=50):", ": "),
|
| 136 |
+
("def out(tag:", " str, n=50):", " "),
|
| 137 |
+
("def out(tag: ", "str, n=50):", "str, "),
|
| 138 |
+
("def out(tag: s", "tr, n=50):", "tr, "),
|
| 139 |
+
("def out(tag: st", "r, n=50):", "r, "),
|
| 140 |
+
("def out(tag: str", ", n=50):", ", n"),
|
| 141 |
+
("def out(tag: str,", " n=50):", " n"),
|
| 142 |
+
("def out(tag: str, ", "n=50):", "n="),
|
| 143 |
+
("def out(tag: str, n", "=50):", "="),
|
| 144 |
+
("def out(tag: str, n=", "50):", "50)"),
|
| 145 |
+
("def out(tag: str, n=5", "0):", "0)"),
|
| 146 |
+
("def out(tag: str, n=50", "):", "):"),
|
| 147 |
+
("def out(tag: str, n=50)", ":", ":"),
|
| 148 |
+
],
|
| 149 |
+
)
|
| 150 |
+
def test_autosuggest_token(text, suggestion, expected):
|
| 151 |
+
event = make_event(text, len(text), suggestion)
|
| 152 |
+
event.current_buffer.insert_text = Mock()
|
| 153 |
+
accept_token(event)
|
| 154 |
+
assert event.current_buffer.insert_text.called
|
| 155 |
+
assert event.current_buffer.insert_text.call_args[0] == (expected,)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@pytest.mark.parametrize(
|
| 159 |
+
"text, suggestion, expected",
|
| 160 |
+
[
|
| 161 |
+
("", "def out(tag: str, n=50):", "d"),
|
| 162 |
+
("d", "ef out(tag: str, n=50):", "e"),
|
| 163 |
+
("de ", "f out(tag: str, n=50):", "f"),
|
| 164 |
+
("def", " out(tag: str, n=50):", " "),
|
| 165 |
+
],
|
| 166 |
+
)
|
| 167 |
+
def test_accept_character(text, suggestion, expected):
|
| 168 |
+
event = make_event(text, len(text), suggestion)
|
| 169 |
+
event.current_buffer.insert_text = Mock()
|
| 170 |
+
accept_character(event)
|
| 171 |
+
assert event.current_buffer.insert_text.called
|
| 172 |
+
assert event.current_buffer.insert_text.call_args[0] == (expected,)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@pytest.mark.parametrize(
|
| 176 |
+
"text, suggestion, expected",
|
| 177 |
+
[
|
| 178 |
+
("", "def out(tag: str, n=50):", "def "),
|
| 179 |
+
("d", "ef out(tag: str, n=50):", "ef "),
|
| 180 |
+
("de", "f out(tag: str, n=50):", "f "),
|
| 181 |
+
("def", " out(tag: str, n=50):", " "),
|
| 182 |
+
# (this is why we also have accept_token)
|
| 183 |
+
("def ", "out(tag: str, n=50):", "out(tag: "),
|
| 184 |
+
],
|
| 185 |
+
)
|
| 186 |
+
def test_accept_word(text, suggestion, expected):
|
| 187 |
+
event = make_event(text, len(text), suggestion)
|
| 188 |
+
event.current_buffer.insert_text = Mock()
|
| 189 |
+
accept_word(event)
|
| 190 |
+
assert event.current_buffer.insert_text.called
|
| 191 |
+
assert event.current_buffer.insert_text.call_args[0] == (expected,)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@pytest.mark.parametrize(
|
| 195 |
+
"text, suggestion, expected, cursor",
|
| 196 |
+
[
|
| 197 |
+
("", "def out(tag: str, n=50):", "def out(tag: str, n=50):", 0),
|
| 198 |
+
("def ", "out(tag: str, n=50):", "out(tag: str, n=50):", 4),
|
| 199 |
+
],
|
| 200 |
+
)
|
| 201 |
+
def test_accept_and_keep_cursor(text, suggestion, expected, cursor):
|
| 202 |
+
event = make_event(text, cursor, suggestion)
|
| 203 |
+
buffer = event.current_buffer
|
| 204 |
+
buffer.insert_text = Mock()
|
| 205 |
+
accept_and_keep_cursor(event)
|
| 206 |
+
assert buffer.insert_text.called
|
| 207 |
+
assert buffer.insert_text.call_args[0] == (expected,)
|
| 208 |
+
assert buffer.cursor_position == cursor
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def test_autosuggest_token_empty():
|
| 212 |
+
full = "def out(tag: str, n=50):"
|
| 213 |
+
event = make_event(full, len(full), "")
|
| 214 |
+
event.current_buffer.insert_text = Mock()
|
| 215 |
+
|
| 216 |
+
with patch(
|
| 217 |
+
"prompt_toolkit.key_binding.bindings.named_commands.forward_word"
|
| 218 |
+
) as forward_word:
|
| 219 |
+
accept_token(event)
|
| 220 |
+
assert not event.current_buffer.insert_text.called
|
| 221 |
+
assert forward_word.called
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_reset_search_buffer():
|
| 225 |
+
event_with_text = Mock()
|
| 226 |
+
event_with_text.current_buffer.document.text = "some text"
|
| 227 |
+
event_with_text.current_buffer.reset = Mock()
|
| 228 |
+
|
| 229 |
+
event_empty = Mock()
|
| 230 |
+
event_empty.current_buffer.document.text = ""
|
| 231 |
+
event_empty.app.layout.focus = Mock()
|
| 232 |
+
|
| 233 |
+
reset_search_buffer(event_with_text)
|
| 234 |
+
event_with_text.current_buffer.reset.assert_called_once()
|
| 235 |
+
|
| 236 |
+
reset_search_buffer(event_empty)
|
| 237 |
+
event_empty.app.layout.focus.assert_called_once_with(DEFAULT_BUFFER)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def test_other_providers():
|
| 241 |
+
"""Ensure that swapping autosuggestions does not break with other providers"""
|
| 242 |
+
provider = AutoSuggestFromHistory()
|
| 243 |
+
ip = get_ipython()
|
| 244 |
+
ip.auto_suggest = provider
|
| 245 |
+
event = Mock()
|
| 246 |
+
event.current_buffer = Buffer()
|
| 247 |
+
assert swap_autosuggestion_up(event) is None
|
| 248 |
+
assert swap_autosuggestion_down(event) is None
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
@pytest.mark.asyncio
|
| 252 |
+
async def test_navigable_provider():
|
| 253 |
+
provider = NavigableAutoSuggestFromHistory()
|
| 254 |
+
history = InMemoryHistory(history_strings=["very_a", "very", "very_b", "very_c"])
|
| 255 |
+
buffer = Buffer(history=history)
|
| 256 |
+
ip = get_ipython()
|
| 257 |
+
ip.auto_suggest = provider
|
| 258 |
+
|
| 259 |
+
async for _ in history.load():
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
+
buffer.cursor_position = 5
|
| 263 |
+
buffer.text = "very"
|
| 264 |
+
|
| 265 |
+
up = swap_autosuggestion_up
|
| 266 |
+
down = swap_autosuggestion_down
|
| 267 |
+
|
| 268 |
+
event = Mock()
|
| 269 |
+
event.current_buffer = buffer
|
| 270 |
+
|
| 271 |
+
def get_suggestion():
|
| 272 |
+
suggestion = provider.get_suggestion(buffer, buffer.document)
|
| 273 |
+
buffer.suggestion = suggestion
|
| 274 |
+
return suggestion
|
| 275 |
+
|
| 276 |
+
assert get_suggestion().text == "_c"
|
| 277 |
+
|
| 278 |
+
# should go up
|
| 279 |
+
up(event)
|
| 280 |
+
assert get_suggestion().text == "_b"
|
| 281 |
+
|
| 282 |
+
# should skip over 'very' which is identical to buffer content
|
| 283 |
+
up(event)
|
| 284 |
+
assert get_suggestion().text == "_a"
|
| 285 |
+
|
| 286 |
+
# should cycle back to beginning
|
| 287 |
+
up(event)
|
| 288 |
+
assert get_suggestion().text == "_c"
|
| 289 |
+
|
| 290 |
+
# should cycle back through end boundary
|
| 291 |
+
down(event)
|
| 292 |
+
assert get_suggestion().text == "_a"
|
| 293 |
+
|
| 294 |
+
down(event)
|
| 295 |
+
assert get_suggestion().text == "_b"
|
| 296 |
+
|
| 297 |
+
down(event)
|
| 298 |
+
assert get_suggestion().text == "_c"
|
| 299 |
+
|
| 300 |
+
down(event)
|
| 301 |
+
assert get_suggestion().text == "_a"
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
@pytest.mark.asyncio
|
| 305 |
+
async def test_navigable_provider_multiline_entries():
|
| 306 |
+
provider = NavigableAutoSuggestFromHistory()
|
| 307 |
+
history = InMemoryHistory(history_strings=["very_a\nvery_b", "very_c"])
|
| 308 |
+
buffer = Buffer(history=history)
|
| 309 |
+
ip = get_ipython()
|
| 310 |
+
ip.auto_suggest = provider
|
| 311 |
+
|
| 312 |
+
async for _ in history.load():
|
| 313 |
+
pass
|
| 314 |
+
|
| 315 |
+
buffer.cursor_position = 5
|
| 316 |
+
buffer.text = "very"
|
| 317 |
+
up = swap_autosuggestion_up
|
| 318 |
+
down = swap_autosuggestion_down
|
| 319 |
+
|
| 320 |
+
event = Mock()
|
| 321 |
+
event.current_buffer = buffer
|
| 322 |
+
|
| 323 |
+
def get_suggestion():
|
| 324 |
+
suggestion = provider.get_suggestion(buffer, buffer.document)
|
| 325 |
+
buffer.suggestion = suggestion
|
| 326 |
+
return suggestion
|
| 327 |
+
|
| 328 |
+
assert get_suggestion().text == "_c"
|
| 329 |
+
|
| 330 |
+
up(event)
|
| 331 |
+
assert get_suggestion().text == "_b"
|
| 332 |
+
|
| 333 |
+
up(event)
|
| 334 |
+
assert get_suggestion().text == "_a"
|
| 335 |
+
|
| 336 |
+
down(event)
|
| 337 |
+
assert get_suggestion().text == "_b"
|
| 338 |
+
|
| 339 |
+
down(event)
|
| 340 |
+
assert get_suggestion().text == "_c"
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def create_session_mock():
|
| 344 |
+
session = Mock()
|
| 345 |
+
session.default_buffer = Buffer()
|
| 346 |
+
return session
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def test_navigable_provider_connection():
|
| 350 |
+
provider = NavigableAutoSuggestFromHistory()
|
| 351 |
+
provider.skip_lines = 1
|
| 352 |
+
|
| 353 |
+
session_1 = create_session_mock()
|
| 354 |
+
provider.connect(session_1)
|
| 355 |
+
|
| 356 |
+
assert provider.skip_lines == 1
|
| 357 |
+
session_1.default_buffer.on_text_insert.fire()
|
| 358 |
+
assert provider.skip_lines == 0
|
| 359 |
+
|
| 360 |
+
session_2 = create_session_mock()
|
| 361 |
+
provider.connect(session_2)
|
| 362 |
+
provider.skip_lines = 2
|
| 363 |
+
|
| 364 |
+
assert provider.skip_lines == 2
|
| 365 |
+
session_2.default_buffer.on_text_insert.fire()
|
| 366 |
+
assert provider.skip_lines == 0
|
| 367 |
+
|
| 368 |
+
provider.skip_lines = 3
|
| 369 |
+
provider.disconnect()
|
| 370 |
+
session_1.default_buffer.on_text_insert.fire()
|
| 371 |
+
session_2.default_buffer.on_text_insert.fire()
|
| 372 |
+
assert provider.skip_lines == 3
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@pytest.fixture
|
| 376 |
+
def ipython_with_prompt():
|
| 377 |
+
ip = get_ipython()
|
| 378 |
+
ip.pt_app = Mock()
|
| 379 |
+
ip.pt_app.key_bindings = create_ipython_shortcuts(ip)
|
| 380 |
+
try:
|
| 381 |
+
yield ip
|
| 382 |
+
finally:
|
| 383 |
+
ip.pt_app = None
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def find_bindings_by_command(command):
|
| 387 |
+
ip = get_ipython()
|
| 388 |
+
return [
|
| 389 |
+
binding
|
| 390 |
+
for binding in ip.pt_app.key_bindings.bindings
|
| 391 |
+
if binding.handler == command
|
| 392 |
+
]
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def test_modify_unique_shortcut(ipython_with_prompt):
|
| 396 |
+
original = find_bindings_by_command(accept_token)
|
| 397 |
+
assert len(original) == 1
|
| 398 |
+
|
| 399 |
+
ipython_with_prompt.shortcuts = [
|
| 400 |
+
{"command": "IPython:auto_suggest.accept_token", "new_keys": ["a", "b", "c"]}
|
| 401 |
+
]
|
| 402 |
+
matched = find_bindings_by_command(accept_token)
|
| 403 |
+
assert len(matched) == 1
|
| 404 |
+
assert list(matched[0].keys) == ["a", "b", "c"]
|
| 405 |
+
assert list(matched[0].keys) != list(original[0].keys)
|
| 406 |
+
assert matched[0].filter == original[0].filter
|
| 407 |
+
|
| 408 |
+
ipython_with_prompt.shortcuts = [
|
| 409 |
+
{"command": "IPython:auto_suggest.accept_token", "new_filter": "always"}
|
| 410 |
+
]
|
| 411 |
+
matched = find_bindings_by_command(accept_token)
|
| 412 |
+
assert len(matched) == 1
|
| 413 |
+
assert list(matched[0].keys) != ["a", "b", "c"]
|
| 414 |
+
assert list(matched[0].keys) == list(original[0].keys)
|
| 415 |
+
assert matched[0].filter != original[0].filter
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def test_disable_shortcut(ipython_with_prompt):
|
| 419 |
+
matched = find_bindings_by_command(accept_token)
|
| 420 |
+
assert len(matched) == 1
|
| 421 |
+
|
| 422 |
+
ipython_with_prompt.shortcuts = [
|
| 423 |
+
{"command": "IPython:auto_suggest.accept_token", "new_keys": []}
|
| 424 |
+
]
|
| 425 |
+
matched = find_bindings_by_command(accept_token)
|
| 426 |
+
assert len(matched) == 0
|
| 427 |
+
|
| 428 |
+
ipython_with_prompt.shortcuts = []
|
| 429 |
+
matched = find_bindings_by_command(accept_token)
|
| 430 |
+
assert len(matched) == 1
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def test_modify_shortcut_with_filters(ipython_with_prompt):
|
| 434 |
+
matched = find_bindings_by_command(skip_over)
|
| 435 |
+
matched_keys = {m.keys[0] for m in matched}
|
| 436 |
+
assert matched_keys == {")", "]", "}", "'", '"'}
|
| 437 |
+
|
| 438 |
+
with pytest.raises(ValueError, match="Multiple shortcuts matching"):
|
| 439 |
+
ipython_with_prompt.shortcuts = [
|
| 440 |
+
{"command": "IPython:auto_match.skip_over", "new_keys": ["x"]}
|
| 441 |
+
]
|
| 442 |
+
|
| 443 |
+
ipython_with_prompt.shortcuts = [
|
| 444 |
+
{
|
| 445 |
+
"command": "IPython:auto_match.skip_over",
|
| 446 |
+
"new_keys": ["x"],
|
| 447 |
+
"match_filter": "focused_insert & auto_match & followed_by_single_quote",
|
| 448 |
+
}
|
| 449 |
+
]
|
| 450 |
+
matched = find_bindings_by_command(skip_over)
|
| 451 |
+
matched_keys = {m.keys[0] for m in matched}
|
| 452 |
+
assert matched_keys == {")", "]", "}", "x", '"'}
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def example_command():
|
| 456 |
+
pass
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def test_add_shortcut_for_new_command(ipython_with_prompt):
|
| 460 |
+
matched = find_bindings_by_command(example_command)
|
| 461 |
+
assert len(matched) == 0
|
| 462 |
+
|
| 463 |
+
with pytest.raises(ValueError, match="example_command is not a known"):
|
| 464 |
+
ipython_with_prompt.shortcuts = [
|
| 465 |
+
{"command": "example_command", "new_keys": ["x"]}
|
| 466 |
+
]
|
| 467 |
+
matched = find_bindings_by_command(example_command)
|
| 468 |
+
assert len(matched) == 0
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def test_modify_shortcut_failure(ipython_with_prompt):
|
| 472 |
+
with pytest.raises(ValueError, match="No shortcuts matching"):
|
| 473 |
+
ipython_with_prompt.shortcuts = [
|
| 474 |
+
{
|
| 475 |
+
"command": "IPython:auto_match.skip_over",
|
| 476 |
+
"match_keys": ["x"],
|
| 477 |
+
"new_keys": ["y"],
|
| 478 |
+
}
|
| 479 |
+
]
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def test_add_shortcut_for_existing_command(ipython_with_prompt):
|
| 483 |
+
matched = find_bindings_by_command(skip_over)
|
| 484 |
+
assert len(matched) == 5
|
| 485 |
+
|
| 486 |
+
with pytest.raises(ValueError, match="Cannot add a shortcut without keys"):
|
| 487 |
+
ipython_with_prompt.shortcuts = [
|
| 488 |
+
{"command": "IPython:auto_match.skip_over", "new_keys": [], "create": True}
|
| 489 |
+
]
|
| 490 |
+
|
| 491 |
+
ipython_with_prompt.shortcuts = [
|
| 492 |
+
{"command": "IPython:auto_match.skip_over", "new_keys": ["x"], "create": True}
|
| 493 |
+
]
|
| 494 |
+
matched = find_bindings_by_command(skip_over)
|
| 495 |
+
assert len(matched) == 6
|
| 496 |
+
|
| 497 |
+
ipython_with_prompt.shortcuts = []
|
| 498 |
+
matched = find_bindings_by_command(skip_over)
|
| 499 |
+
assert len(matched) == 5
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def test_setting_shortcuts_before_pt_app_init():
|
| 503 |
+
ipython = get_ipython()
|
| 504 |
+
assert ipython.pt_app is None
|
| 505 |
+
shortcuts = [
|
| 506 |
+
{"command": "IPython:auto_match.skip_over", "new_keys": ["x"], "create": True}
|
| 507 |
+
]
|
| 508 |
+
ipython.shortcuts = shortcuts
|
| 509 |
+
assert ipython.shortcuts == shortcuts
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (395 Bytes). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/decorators.cpython-310.pyc
ADDED
|
Binary file (6.23 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/globalipapp.cpython-310.pyc
ADDED
|
Binary file (2.57 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/ipunittest.cpython-310.pyc
ADDED
|
Binary file (5.46 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/skipdoctest.cpython-310.pyc
ADDED
|
Binary file (920 Bytes). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/__pycache__/tools.cpython-310.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/README.txt
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=======================================================
|
| 2 |
+
Nose plugin with IPython and extension module support
|
| 3 |
+
=======================================================
|
| 4 |
+
|
| 5 |
+
This directory provides the key functionality for test support that IPython
|
| 6 |
+
needs as a nose plugin, which can be installed for use in projects other than
|
| 7 |
+
IPython.
|
| 8 |
+
|
| 9 |
+
The presence of a Makefile here is mostly for development and debugging
|
| 10 |
+
purposes as it only provides a few shorthand commands. You can manually
|
| 11 |
+
install the plugin by using standard Python procedures (``setup.py install``
|
| 12 |
+
with appropriate arguments).
|
| 13 |
+
|
| 14 |
+
To install the plugin using the Makefile, edit its first line to reflect where
|
| 15 |
+
you'd like the installation.
|
| 16 |
+
|
| 17 |
+
Once you've set the prefix, simply build/install the plugin with::
|
| 18 |
+
|
| 19 |
+
make
|
| 20 |
+
|
| 21 |
+
and run the tests with::
|
| 22 |
+
|
| 23 |
+
make test
|
| 24 |
+
|
| 25 |
+
You should see output similar to::
|
| 26 |
+
|
| 27 |
+
maqroll[plugin]> make test
|
| 28 |
+
nosetests -s --with-ipdoctest --doctest-tests dtexample.py
|
| 29 |
+
..
|
| 30 |
+
----------------------------------------------------------------------
|
| 31 |
+
Ran 2 tests in 0.016s
|
| 32 |
+
|
| 33 |
+
OK
|
| 34 |
+
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__init__.py
ADDED
|
File without changes
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (245 Bytes). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/dtexample.cpython-310.pyc
ADDED
|
Binary file (3.6 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/ipdoctest.cpython-310.pyc
ADDED
|
Binary file (8.62 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/pytest_ipdoctest.cpython-310.pyc
ADDED
|
Binary file (25.1 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/setup.cpython-310.pyc
ADDED
|
Binary file (678 Bytes). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simple.cpython-310.pyc
ADDED
|
Binary file (1.09 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/simplevars.cpython-310.pyc
ADDED
|
Binary file (282 Bytes). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_ipdoctest.cpython-310.pyc
ADDED
|
Binary file (2.53 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/__pycache__/test_refs.cpython-310.pyc
ADDED
|
Binary file (1.12 kB). View file
|
|
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/dtexample.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
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|
+
This file just contains doctests both using plain python and IPython prompts.
|
| 4 |
+
All tests should be loaded by nose.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def pyfunc():
|
| 11 |
+
"""Some pure python tests...
|
| 12 |
+
|
| 13 |
+
>>> pyfunc()
|
| 14 |
+
'pyfunc'
|
| 15 |
+
|
| 16 |
+
>>> import os
|
| 17 |
+
|
| 18 |
+
>>> 2+3
|
| 19 |
+
5
|
| 20 |
+
|
| 21 |
+
>>> for i in range(3):
|
| 22 |
+
... print(i, end=' ')
|
| 23 |
+
... print(i+1, end=' ')
|
| 24 |
+
...
|
| 25 |
+
0 1 1 2 2 3
|
| 26 |
+
"""
|
| 27 |
+
return 'pyfunc'
|
| 28 |
+
|
| 29 |
+
def ipfunc():
|
| 30 |
+
"""Some ipython tests...
|
| 31 |
+
|
| 32 |
+
In [1]: import os
|
| 33 |
+
|
| 34 |
+
In [3]: 2+3
|
| 35 |
+
Out[3]: 5
|
| 36 |
+
|
| 37 |
+
In [26]: for i in range(3):
|
| 38 |
+
....: print(i, end=' ')
|
| 39 |
+
....: print(i+1, end=' ')
|
| 40 |
+
....:
|
| 41 |
+
0 1 1 2 2 3
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
It's OK to use '_' for the last result, but do NOT try to use IPython's
|
| 45 |
+
numbered history of _NN outputs, since those won't exist under the
|
| 46 |
+
doctest environment:
|
| 47 |
+
|
| 48 |
+
In [7]: 'hi'
|
| 49 |
+
Out[7]: 'hi'
|
| 50 |
+
|
| 51 |
+
In [8]: print(repr(_))
|
| 52 |
+
'hi'
|
| 53 |
+
|
| 54 |
+
In [7]: 3+4
|
| 55 |
+
Out[7]: 7
|
| 56 |
+
|
| 57 |
+
In [8]: _+3
|
| 58 |
+
Out[8]: 10
|
| 59 |
+
|
| 60 |
+
In [9]: ipfunc()
|
| 61 |
+
Out[9]: 'ipfunc'
|
| 62 |
+
"""
|
| 63 |
+
return "ipfunc"
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def ipos():
|
| 67 |
+
"""Examples that access the operating system work:
|
| 68 |
+
|
| 69 |
+
In [1]: !echo hello
|
| 70 |
+
hello
|
| 71 |
+
|
| 72 |
+
In [2]: !echo hello > /tmp/foo_iptest
|
| 73 |
+
|
| 74 |
+
In [3]: !cat /tmp/foo_iptest
|
| 75 |
+
hello
|
| 76 |
+
|
| 77 |
+
In [4]: rm -f /tmp/foo_iptest
|
| 78 |
+
"""
|
| 79 |
+
pass
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
ipos.__skip_doctest__ = os.name == "nt"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def ranfunc():
|
| 86 |
+
"""A function with some random output.
|
| 87 |
+
|
| 88 |
+
Normal examples are verified as usual:
|
| 89 |
+
>>> 1+3
|
| 90 |
+
4
|
| 91 |
+
|
| 92 |
+
But if you put '# random' in the output, it is ignored:
|
| 93 |
+
>>> 1+3
|
| 94 |
+
junk goes here... # random
|
| 95 |
+
|
| 96 |
+
>>> 1+2
|
| 97 |
+
again, anything goes #random
|
| 98 |
+
if multiline, the random mark is only needed once.
|
| 99 |
+
|
| 100 |
+
>>> 1+2
|
| 101 |
+
You can also put the random marker at the end:
|
| 102 |
+
# random
|
| 103 |
+
|
| 104 |
+
>>> 1+2
|
| 105 |
+
# random
|
| 106 |
+
.. or at the beginning.
|
| 107 |
+
|
| 108 |
+
More correct input is properly verified:
|
| 109 |
+
>>> ranfunc()
|
| 110 |
+
'ranfunc'
|
| 111 |
+
"""
|
| 112 |
+
return 'ranfunc'
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def random_all():
|
| 116 |
+
"""A function where we ignore the output of ALL examples.
|
| 117 |
+
|
| 118 |
+
Examples:
|
| 119 |
+
|
| 120 |
+
# all-random
|
| 121 |
+
|
| 122 |
+
This mark tells the testing machinery that all subsequent examples should
|
| 123 |
+
be treated as random (ignoring their output). They are still executed,
|
| 124 |
+
so if a they raise an error, it will be detected as such, but their
|
| 125 |
+
output is completely ignored.
|
| 126 |
+
|
| 127 |
+
>>> 1+3
|
| 128 |
+
junk goes here...
|
| 129 |
+
|
| 130 |
+
>>> 1+3
|
| 131 |
+
klasdfj;
|
| 132 |
+
|
| 133 |
+
>>> 1+2
|
| 134 |
+
again, anything goes
|
| 135 |
+
blah...
|
| 136 |
+
"""
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
def iprand():
|
| 140 |
+
"""Some ipython tests with random output.
|
| 141 |
+
|
| 142 |
+
In [7]: 3+4
|
| 143 |
+
Out[7]: 7
|
| 144 |
+
|
| 145 |
+
In [8]: print('hello')
|
| 146 |
+
world # random
|
| 147 |
+
|
| 148 |
+
In [9]: iprand()
|
| 149 |
+
Out[9]: 'iprand'
|
| 150 |
+
"""
|
| 151 |
+
return 'iprand'
|
| 152 |
+
|
| 153 |
+
def iprand_all():
|
| 154 |
+
"""Some ipython tests with fully random output.
|
| 155 |
+
|
| 156 |
+
# all-random
|
| 157 |
+
|
| 158 |
+
In [7]: 1
|
| 159 |
+
Out[7]: 99
|
| 160 |
+
|
| 161 |
+
In [8]: print('hello')
|
| 162 |
+
world
|
| 163 |
+
|
| 164 |
+
In [9]: iprand_all()
|
| 165 |
+
Out[9]: 'junk'
|
| 166 |
+
"""
|
| 167 |
+
return 'iprand_all'
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/ipdoctest.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Nose Plugin that supports IPython doctests.
|
| 2 |
+
|
| 3 |
+
Limitations:
|
| 4 |
+
|
| 5 |
+
- When generating examples for use as doctests, make sure that you have
|
| 6 |
+
pretty-printing OFF. This can be done either by setting the
|
| 7 |
+
``PlainTextFormatter.pprint`` option in your configuration file to False, or
|
| 8 |
+
by interactively disabling it with %Pprint. This is required so that IPython
|
| 9 |
+
output matches that of normal Python, which is used by doctest for internal
|
| 10 |
+
execution.
|
| 11 |
+
|
| 12 |
+
- Do not rely on specific prompt numbers for results (such as using
|
| 13 |
+
'_34==True', for example). For IPython tests run via an external process the
|
| 14 |
+
prompt numbers may be different, and IPython tests run as normal python code
|
| 15 |
+
won't even have these special _NN variables set at all.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
#-----------------------------------------------------------------------------
|
| 19 |
+
# Module imports
|
| 20 |
+
|
| 21 |
+
# From the standard library
|
| 22 |
+
import doctest
|
| 23 |
+
import logging
|
| 24 |
+
import re
|
| 25 |
+
|
| 26 |
+
from testpath import modified_env
|
| 27 |
+
|
| 28 |
+
#-----------------------------------------------------------------------------
|
| 29 |
+
# Module globals and other constants
|
| 30 |
+
#-----------------------------------------------------------------------------
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
#-----------------------------------------------------------------------------
|
| 36 |
+
# Classes and functions
|
| 37 |
+
#-----------------------------------------------------------------------------
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DocTestFinder(doctest.DocTestFinder):
|
| 41 |
+
def _get_test(self, obj, name, module, globs, source_lines):
|
| 42 |
+
test = super()._get_test(obj, name, module, globs, source_lines)
|
| 43 |
+
|
| 44 |
+
if bool(getattr(obj, "__skip_doctest__", False)) and test is not None:
|
| 45 |
+
for example in test.examples:
|
| 46 |
+
example.options[doctest.SKIP] = True
|
| 47 |
+
|
| 48 |
+
return test
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class IPDoctestOutputChecker(doctest.OutputChecker):
|
| 52 |
+
"""Second-chance checker with support for random tests.
|
| 53 |
+
|
| 54 |
+
If the default comparison doesn't pass, this checker looks in the expected
|
| 55 |
+
output string for flags that tell us to ignore the output.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
random_re = re.compile(r'#\s*random\s+')
|
| 59 |
+
|
| 60 |
+
def check_output(self, want, got, optionflags):
|
| 61 |
+
"""Check output, accepting special markers embedded in the output.
|
| 62 |
+
|
| 63 |
+
If the output didn't pass the default validation but the special string
|
| 64 |
+
'#random' is included, we accept it."""
|
| 65 |
+
|
| 66 |
+
# Let the original tester verify first, in case people have valid tests
|
| 67 |
+
# that happen to have a comment saying '#random' embedded in.
|
| 68 |
+
ret = doctest.OutputChecker.check_output(self, want, got,
|
| 69 |
+
optionflags)
|
| 70 |
+
if not ret and self.random_re.search(want):
|
| 71 |
+
# print('RANDOM OK:',want, file=sys.stderr) # dbg
|
| 72 |
+
return True
|
| 73 |
+
|
| 74 |
+
return ret
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
# A simple subclassing of the original with a different class name, so we can
|
| 78 |
+
# distinguish and treat differently IPython examples from pure python ones.
|
| 79 |
+
class IPExample(doctest.Example): pass
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class IPDocTestParser(doctest.DocTestParser):
|
| 83 |
+
"""
|
| 84 |
+
A class used to parse strings containing doctest examples.
|
| 85 |
+
|
| 86 |
+
Note: This is a version modified to properly recognize IPython input and
|
| 87 |
+
convert any IPython examples into valid Python ones.
|
| 88 |
+
"""
|
| 89 |
+
# This regular expression is used to find doctest examples in a
|
| 90 |
+
# string. It defines three groups: `source` is the source code
|
| 91 |
+
# (including leading indentation and prompts); `indent` is the
|
| 92 |
+
# indentation of the first (PS1) line of the source code; and
|
| 93 |
+
# `want` is the expected output (including leading indentation).
|
| 94 |
+
|
| 95 |
+
# Classic Python prompts or default IPython ones
|
| 96 |
+
_PS1_PY = r'>>>'
|
| 97 |
+
_PS2_PY = r'\.\.\.'
|
| 98 |
+
|
| 99 |
+
_PS1_IP = r'In\ \[\d+\]:'
|
| 100 |
+
_PS2_IP = r'\ \ \ \.\.\.+:'
|
| 101 |
+
|
| 102 |
+
_RE_TPL = r'''
|
| 103 |
+
# Source consists of a PS1 line followed by zero or more PS2 lines.
|
| 104 |
+
(?P<source>
|
| 105 |
+
(?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
|
| 106 |
+
(?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
|
| 107 |
+
\n? # a newline
|
| 108 |
+
# Want consists of any non-blank lines that do not start with PS1.
|
| 109 |
+
(?P<want> (?:(?![ ]*$) # Not a blank line
|
| 110 |
+
(?![ ]*%s) # Not a line starting with PS1
|
| 111 |
+
(?![ ]*%s) # Not a line starting with PS2
|
| 112 |
+
.*$\n? # But any other line
|
| 113 |
+
)*)
|
| 114 |
+
'''
|
| 115 |
+
|
| 116 |
+
_EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),
|
| 117 |
+
re.MULTILINE | re.VERBOSE)
|
| 118 |
+
|
| 119 |
+
_EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),
|
| 120 |
+
re.MULTILINE | re.VERBOSE)
|
| 121 |
+
|
| 122 |
+
# Mark a test as being fully random. In this case, we simply append the
|
| 123 |
+
# random marker ('#random') to each individual example's output. This way
|
| 124 |
+
# we don't need to modify any other code.
|
| 125 |
+
_RANDOM_TEST = re.compile(r'#\s*all-random\s+')
|
| 126 |
+
|
| 127 |
+
def ip2py(self,source):
|
| 128 |
+
"""Convert input IPython source into valid Python."""
|
| 129 |
+
block = _ip.input_transformer_manager.transform_cell(source)
|
| 130 |
+
if len(block.splitlines()) == 1:
|
| 131 |
+
return _ip.prefilter(block)
|
| 132 |
+
else:
|
| 133 |
+
return block
|
| 134 |
+
|
| 135 |
+
def parse(self, string, name='<string>'):
|
| 136 |
+
"""
|
| 137 |
+
Divide the given string into examples and intervening text,
|
| 138 |
+
and return them as a list of alternating Examples and strings.
|
| 139 |
+
Line numbers for the Examples are 0-based. The optional
|
| 140 |
+
argument `name` is a name identifying this string, and is only
|
| 141 |
+
used for error messages.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
# print('Parse string:\n',string) # dbg
|
| 145 |
+
|
| 146 |
+
string = string.expandtabs()
|
| 147 |
+
# If all lines begin with the same indentation, then strip it.
|
| 148 |
+
min_indent = self._min_indent(string)
|
| 149 |
+
if min_indent > 0:
|
| 150 |
+
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
|
| 151 |
+
|
| 152 |
+
output = []
|
| 153 |
+
charno, lineno = 0, 0
|
| 154 |
+
|
| 155 |
+
# We make 'all random' tests by adding the '# random' mark to every
|
| 156 |
+
# block of output in the test.
|
| 157 |
+
if self._RANDOM_TEST.search(string):
|
| 158 |
+
random_marker = '\n# random'
|
| 159 |
+
else:
|
| 160 |
+
random_marker = ''
|
| 161 |
+
|
| 162 |
+
# Whether to convert the input from ipython to python syntax
|
| 163 |
+
ip2py = False
|
| 164 |
+
# Find all doctest examples in the string. First, try them as Python
|
| 165 |
+
# examples, then as IPython ones
|
| 166 |
+
terms = list(self._EXAMPLE_RE_PY.finditer(string))
|
| 167 |
+
if terms:
|
| 168 |
+
# Normal Python example
|
| 169 |
+
Example = doctest.Example
|
| 170 |
+
else:
|
| 171 |
+
# It's an ipython example.
|
| 172 |
+
terms = list(self._EXAMPLE_RE_IP.finditer(string))
|
| 173 |
+
Example = IPExample
|
| 174 |
+
ip2py = True
|
| 175 |
+
|
| 176 |
+
for m in terms:
|
| 177 |
+
# Add the pre-example text to `output`.
|
| 178 |
+
output.append(string[charno:m.start()])
|
| 179 |
+
# Update lineno (lines before this example)
|
| 180 |
+
lineno += string.count('\n', charno, m.start())
|
| 181 |
+
# Extract info from the regexp match.
|
| 182 |
+
(source, options, want, exc_msg) = \
|
| 183 |
+
self._parse_example(m, name, lineno,ip2py)
|
| 184 |
+
|
| 185 |
+
# Append the random-output marker (it defaults to empty in most
|
| 186 |
+
# cases, it's only non-empty for 'all-random' tests):
|
| 187 |
+
want += random_marker
|
| 188 |
+
|
| 189 |
+
# Create an Example, and add it to the list.
|
| 190 |
+
if not self._IS_BLANK_OR_COMMENT(source):
|
| 191 |
+
output.append(Example(source, want, exc_msg,
|
| 192 |
+
lineno=lineno,
|
| 193 |
+
indent=min_indent+len(m.group('indent')),
|
| 194 |
+
options=options))
|
| 195 |
+
# Update lineno (lines inside this example)
|
| 196 |
+
lineno += string.count('\n', m.start(), m.end())
|
| 197 |
+
# Update charno.
|
| 198 |
+
charno = m.end()
|
| 199 |
+
# Add any remaining post-example text to `output`.
|
| 200 |
+
output.append(string[charno:])
|
| 201 |
+
return output
|
| 202 |
+
|
| 203 |
+
def _parse_example(self, m, name, lineno,ip2py=False):
|
| 204 |
+
"""
|
| 205 |
+
Given a regular expression match from `_EXAMPLE_RE` (`m`),
|
| 206 |
+
return a pair `(source, want)`, where `source` is the matched
|
| 207 |
+
example's source code (with prompts and indentation stripped);
|
| 208 |
+
and `want` is the example's expected output (with indentation
|
| 209 |
+
stripped).
|
| 210 |
+
|
| 211 |
+
`name` is the string's name, and `lineno` is the line number
|
| 212 |
+
where the example starts; both are used for error messages.
|
| 213 |
+
|
| 214 |
+
Optional:
|
| 215 |
+
`ip2py`: if true, filter the input via IPython to convert the syntax
|
| 216 |
+
into valid python.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
# Get the example's indentation level.
|
| 220 |
+
indent = len(m.group('indent'))
|
| 221 |
+
|
| 222 |
+
# Divide source into lines; check that they're properly
|
| 223 |
+
# indented; and then strip their indentation & prompts.
|
| 224 |
+
source_lines = m.group('source').split('\n')
|
| 225 |
+
|
| 226 |
+
# We're using variable-length input prompts
|
| 227 |
+
ps1 = m.group('ps1')
|
| 228 |
+
ps2 = m.group('ps2')
|
| 229 |
+
ps1_len = len(ps1)
|
| 230 |
+
|
| 231 |
+
self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)
|
| 232 |
+
if ps2:
|
| 233 |
+
self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
|
| 234 |
+
|
| 235 |
+
source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])
|
| 236 |
+
|
| 237 |
+
if ip2py:
|
| 238 |
+
# Convert source input from IPython into valid Python syntax
|
| 239 |
+
source = self.ip2py(source)
|
| 240 |
+
|
| 241 |
+
# Divide want into lines; check that it's properly indented; and
|
| 242 |
+
# then strip the indentation. Spaces before the last newline should
|
| 243 |
+
# be preserved, so plain rstrip() isn't good enough.
|
| 244 |
+
want = m.group('want')
|
| 245 |
+
want_lines = want.split('\n')
|
| 246 |
+
if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
|
| 247 |
+
del want_lines[-1] # forget final newline & spaces after it
|
| 248 |
+
self._check_prefix(want_lines, ' '*indent, name,
|
| 249 |
+
lineno + len(source_lines))
|
| 250 |
+
|
| 251 |
+
# Remove ipython output prompt that might be present in the first line
|
| 252 |
+
want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])
|
| 253 |
+
|
| 254 |
+
want = '\n'.join([wl[indent:] for wl in want_lines])
|
| 255 |
+
|
| 256 |
+
# If `want` contains a traceback message, then extract it.
|
| 257 |
+
m = self._EXCEPTION_RE.match(want)
|
| 258 |
+
if m:
|
| 259 |
+
exc_msg = m.group('msg')
|
| 260 |
+
else:
|
| 261 |
+
exc_msg = None
|
| 262 |
+
|
| 263 |
+
# Extract options from the source.
|
| 264 |
+
options = self._find_options(source, name, lineno)
|
| 265 |
+
|
| 266 |
+
return source, options, want, exc_msg
|
| 267 |
+
|
| 268 |
+
def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
|
| 269 |
+
"""
|
| 270 |
+
Given the lines of a source string (including prompts and
|
| 271 |
+
leading indentation), check to make sure that every prompt is
|
| 272 |
+
followed by a space character. If any line is not followed by
|
| 273 |
+
a space character, then raise ValueError.
|
| 274 |
+
|
| 275 |
+
Note: IPython-modified version which takes the input prompt length as a
|
| 276 |
+
parameter, so that prompts of variable length can be dealt with.
|
| 277 |
+
"""
|
| 278 |
+
space_idx = indent+ps1_len
|
| 279 |
+
min_len = space_idx+1
|
| 280 |
+
for i, line in enumerate(lines):
|
| 281 |
+
if len(line) >= min_len and line[space_idx] != ' ':
|
| 282 |
+
raise ValueError('line %r of the docstring for %s '
|
| 283 |
+
'lacks blank after %s: %r' %
|
| 284 |
+
(lineno+i+1, name,
|
| 285 |
+
line[indent:space_idx], line))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
SKIP = doctest.register_optionflag('SKIP')
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class IPDocTestRunner(doctest.DocTestRunner,object):
|
| 292 |
+
"""Test runner that synchronizes the IPython namespace with test globals.
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
def run(self, test, compileflags=None, out=None, clear_globs=True):
|
| 296 |
+
# Override terminal size to standardise traceback format
|
| 297 |
+
with modified_env({'COLUMNS': '80', 'LINES': '24'}):
|
| 298 |
+
return super(IPDocTestRunner,self).run(test,
|
| 299 |
+
compileflags,out,clear_globs)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/pytest_ipdoctest.py
ADDED
|
@@ -0,0 +1,879 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Based on Pytest doctest.py
|
| 2 |
+
# Original license:
|
| 3 |
+
# The MIT License (MIT)
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) 2004-2021 Holger Krekel and others
|
| 6 |
+
"""Discover and run ipdoctests in modules and test files."""
|
| 7 |
+
import bdb
|
| 8 |
+
import builtins
|
| 9 |
+
import inspect
|
| 10 |
+
import os
|
| 11 |
+
import platform
|
| 12 |
+
import sys
|
| 13 |
+
import traceback
|
| 14 |
+
import types
|
| 15 |
+
import warnings
|
| 16 |
+
from contextlib import contextmanager
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import (
|
| 19 |
+
TYPE_CHECKING,
|
| 20 |
+
Any,
|
| 21 |
+
Callable,
|
| 22 |
+
Dict,
|
| 23 |
+
Generator,
|
| 24 |
+
Iterable,
|
| 25 |
+
List,
|
| 26 |
+
Optional,
|
| 27 |
+
Pattern,
|
| 28 |
+
Sequence,
|
| 29 |
+
Tuple,
|
| 30 |
+
Type,
|
| 31 |
+
Union,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
import pytest
|
| 35 |
+
from _pytest import outcomes
|
| 36 |
+
from _pytest._code.code import ExceptionInfo, ReprFileLocation, TerminalRepr
|
| 37 |
+
from _pytest._io import TerminalWriter
|
| 38 |
+
from _pytest.compat import safe_getattr
|
| 39 |
+
from _pytest.config import Config
|
| 40 |
+
from _pytest.config.argparsing import Parser
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
from _pytest.fixtures import TopRequest as FixtureRequest
|
| 44 |
+
except ImportError:
|
| 45 |
+
from _pytest.fixtures import FixtureRequest
|
| 46 |
+
from _pytest.nodes import Collector
|
| 47 |
+
from _pytest.outcomes import OutcomeException
|
| 48 |
+
from _pytest.pathlib import fnmatch_ex, import_path
|
| 49 |
+
from _pytest.python_api import approx
|
| 50 |
+
from _pytest.warning_types import PytestWarning
|
| 51 |
+
|
| 52 |
+
if TYPE_CHECKING:
|
| 53 |
+
import doctest
|
| 54 |
+
|
| 55 |
+
from .ipdoctest import IPDoctestOutputChecker
|
| 56 |
+
|
| 57 |
+
DOCTEST_REPORT_CHOICE_NONE = "none"
|
| 58 |
+
DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
|
| 59 |
+
DOCTEST_REPORT_CHOICE_NDIFF = "ndiff"
|
| 60 |
+
DOCTEST_REPORT_CHOICE_UDIFF = "udiff"
|
| 61 |
+
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = "only_first_failure"
|
| 62 |
+
|
| 63 |
+
DOCTEST_REPORT_CHOICES = (
|
| 64 |
+
DOCTEST_REPORT_CHOICE_NONE,
|
| 65 |
+
DOCTEST_REPORT_CHOICE_CDIFF,
|
| 66 |
+
DOCTEST_REPORT_CHOICE_NDIFF,
|
| 67 |
+
DOCTEST_REPORT_CHOICE_UDIFF,
|
| 68 |
+
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Lazy definition of runner class
|
| 72 |
+
RUNNER_CLASS = None
|
| 73 |
+
# Lazy definition of output checker class
|
| 74 |
+
CHECKER_CLASS: Optional[Type["IPDoctestOutputChecker"]] = None
|
| 75 |
+
|
| 76 |
+
pytest_version = tuple([int(part) for part in pytest.__version__.split(".")])
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def pytest_addoption(parser: Parser) -> None:
|
| 80 |
+
parser.addini(
|
| 81 |
+
"ipdoctest_optionflags",
|
| 82 |
+
"option flags for ipdoctests",
|
| 83 |
+
type="args",
|
| 84 |
+
default=["ELLIPSIS"],
|
| 85 |
+
)
|
| 86 |
+
parser.addini(
|
| 87 |
+
"ipdoctest_encoding", "encoding used for ipdoctest files", default="utf-8"
|
| 88 |
+
)
|
| 89 |
+
group = parser.getgroup("collect")
|
| 90 |
+
group.addoption(
|
| 91 |
+
"--ipdoctest-modules",
|
| 92 |
+
action="store_true",
|
| 93 |
+
default=False,
|
| 94 |
+
help="run ipdoctests in all .py modules",
|
| 95 |
+
dest="ipdoctestmodules",
|
| 96 |
+
)
|
| 97 |
+
group.addoption(
|
| 98 |
+
"--ipdoctest-report",
|
| 99 |
+
type=str.lower,
|
| 100 |
+
default="udiff",
|
| 101 |
+
help="choose another output format for diffs on ipdoctest failure",
|
| 102 |
+
choices=DOCTEST_REPORT_CHOICES,
|
| 103 |
+
dest="ipdoctestreport",
|
| 104 |
+
)
|
| 105 |
+
group.addoption(
|
| 106 |
+
"--ipdoctest-glob",
|
| 107 |
+
action="append",
|
| 108 |
+
default=[],
|
| 109 |
+
metavar="pat",
|
| 110 |
+
help="ipdoctests file matching pattern, default: test*.txt",
|
| 111 |
+
dest="ipdoctestglob",
|
| 112 |
+
)
|
| 113 |
+
group.addoption(
|
| 114 |
+
"--ipdoctest-ignore-import-errors",
|
| 115 |
+
action="store_true",
|
| 116 |
+
default=False,
|
| 117 |
+
help="ignore ipdoctest ImportErrors",
|
| 118 |
+
dest="ipdoctest_ignore_import_errors",
|
| 119 |
+
)
|
| 120 |
+
group.addoption(
|
| 121 |
+
"--ipdoctest-continue-on-failure",
|
| 122 |
+
action="store_true",
|
| 123 |
+
default=False,
|
| 124 |
+
help="for a given ipdoctest, continue to run after the first failure",
|
| 125 |
+
dest="ipdoctest_continue_on_failure",
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def pytest_unconfigure() -> None:
|
| 130 |
+
global RUNNER_CLASS
|
| 131 |
+
|
| 132 |
+
RUNNER_CLASS = None
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def pytest_collect_file(
|
| 136 |
+
file_path: Path,
|
| 137 |
+
parent: Collector,
|
| 138 |
+
) -> Optional[Union["IPDoctestModule", "IPDoctestTextfile"]]:
|
| 139 |
+
config = parent.config
|
| 140 |
+
if file_path.suffix == ".py":
|
| 141 |
+
if config.option.ipdoctestmodules and not any(
|
| 142 |
+
(_is_setup_py(file_path), _is_main_py(file_path))
|
| 143 |
+
):
|
| 144 |
+
mod: IPDoctestModule = IPDoctestModule.from_parent(parent, path=file_path)
|
| 145 |
+
return mod
|
| 146 |
+
elif _is_ipdoctest(config, file_path, parent):
|
| 147 |
+
txt: IPDoctestTextfile = IPDoctestTextfile.from_parent(parent, path=file_path)
|
| 148 |
+
return txt
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if pytest_version[0] < 7:
|
| 153 |
+
_collect_file = pytest_collect_file
|
| 154 |
+
|
| 155 |
+
def pytest_collect_file(
|
| 156 |
+
path,
|
| 157 |
+
parent: Collector,
|
| 158 |
+
) -> Optional[Union["IPDoctestModule", "IPDoctestTextfile"]]:
|
| 159 |
+
return _collect_file(Path(path), parent)
|
| 160 |
+
|
| 161 |
+
_import_path = import_path
|
| 162 |
+
|
| 163 |
+
def import_path(path, root):
|
| 164 |
+
import py.path
|
| 165 |
+
|
| 166 |
+
return _import_path(py.path.local(path))
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def _is_setup_py(path: Path) -> bool:
|
| 170 |
+
if path.name != "setup.py":
|
| 171 |
+
return False
|
| 172 |
+
contents = path.read_bytes()
|
| 173 |
+
return b"setuptools" in contents or b"distutils" in contents
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _is_ipdoctest(config: Config, path: Path, parent: Collector) -> bool:
|
| 177 |
+
if path.suffix in (".txt", ".rst") and parent.session.isinitpath(path):
|
| 178 |
+
return True
|
| 179 |
+
globs = config.getoption("ipdoctestglob") or ["test*.txt"]
|
| 180 |
+
return any(fnmatch_ex(glob, path) for glob in globs)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _is_main_py(path: Path) -> bool:
|
| 184 |
+
return path.name == "__main__.py"
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class ReprFailDoctest(TerminalRepr):
|
| 188 |
+
def __init__(
|
| 189 |
+
self, reprlocation_lines: Sequence[Tuple[ReprFileLocation, Sequence[str]]]
|
| 190 |
+
) -> None:
|
| 191 |
+
self.reprlocation_lines = reprlocation_lines
|
| 192 |
+
|
| 193 |
+
def toterminal(self, tw: TerminalWriter) -> None:
|
| 194 |
+
for reprlocation, lines in self.reprlocation_lines:
|
| 195 |
+
for line in lines:
|
| 196 |
+
tw.line(line)
|
| 197 |
+
reprlocation.toterminal(tw)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class MultipleDoctestFailures(Exception):
|
| 201 |
+
def __init__(self, failures: Sequence["doctest.DocTestFailure"]) -> None:
|
| 202 |
+
super().__init__()
|
| 203 |
+
self.failures = failures
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _init_runner_class() -> Type["IPDocTestRunner"]:
|
| 207 |
+
import doctest
|
| 208 |
+
from .ipdoctest import IPDocTestRunner
|
| 209 |
+
|
| 210 |
+
class PytestDoctestRunner(IPDocTestRunner):
|
| 211 |
+
"""Runner to collect failures.
|
| 212 |
+
|
| 213 |
+
Note that the out variable in this case is a list instead of a
|
| 214 |
+
stdout-like object.
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
def __init__(
|
| 218 |
+
self,
|
| 219 |
+
checker: Optional["IPDoctestOutputChecker"] = None,
|
| 220 |
+
verbose: Optional[bool] = None,
|
| 221 |
+
optionflags: int = 0,
|
| 222 |
+
continue_on_failure: bool = True,
|
| 223 |
+
) -> None:
|
| 224 |
+
super().__init__(checker=checker, verbose=verbose, optionflags=optionflags)
|
| 225 |
+
self.continue_on_failure = continue_on_failure
|
| 226 |
+
|
| 227 |
+
def report_failure(
|
| 228 |
+
self,
|
| 229 |
+
out,
|
| 230 |
+
test: "doctest.DocTest",
|
| 231 |
+
example: "doctest.Example",
|
| 232 |
+
got: str,
|
| 233 |
+
) -> None:
|
| 234 |
+
failure = doctest.DocTestFailure(test, example, got)
|
| 235 |
+
if self.continue_on_failure:
|
| 236 |
+
out.append(failure)
|
| 237 |
+
else:
|
| 238 |
+
raise failure
|
| 239 |
+
|
| 240 |
+
def report_unexpected_exception(
|
| 241 |
+
self,
|
| 242 |
+
out,
|
| 243 |
+
test: "doctest.DocTest",
|
| 244 |
+
example: "doctest.Example",
|
| 245 |
+
exc_info: Tuple[Type[BaseException], BaseException, types.TracebackType],
|
| 246 |
+
) -> None:
|
| 247 |
+
if isinstance(exc_info[1], OutcomeException):
|
| 248 |
+
raise exc_info[1]
|
| 249 |
+
if isinstance(exc_info[1], bdb.BdbQuit):
|
| 250 |
+
outcomes.exit("Quitting debugger")
|
| 251 |
+
failure = doctest.UnexpectedException(test, example, exc_info)
|
| 252 |
+
if self.continue_on_failure:
|
| 253 |
+
out.append(failure)
|
| 254 |
+
else:
|
| 255 |
+
raise failure
|
| 256 |
+
|
| 257 |
+
return PytestDoctestRunner
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _get_runner(
|
| 261 |
+
checker: Optional["IPDoctestOutputChecker"] = None,
|
| 262 |
+
verbose: Optional[bool] = None,
|
| 263 |
+
optionflags: int = 0,
|
| 264 |
+
continue_on_failure: bool = True,
|
| 265 |
+
) -> "IPDocTestRunner":
|
| 266 |
+
# We need this in order to do a lazy import on doctest
|
| 267 |
+
global RUNNER_CLASS
|
| 268 |
+
if RUNNER_CLASS is None:
|
| 269 |
+
RUNNER_CLASS = _init_runner_class()
|
| 270 |
+
# Type ignored because the continue_on_failure argument is only defined on
|
| 271 |
+
# PytestDoctestRunner, which is lazily defined so can't be used as a type.
|
| 272 |
+
return RUNNER_CLASS( # type: ignore
|
| 273 |
+
checker=checker,
|
| 274 |
+
verbose=verbose,
|
| 275 |
+
optionflags=optionflags,
|
| 276 |
+
continue_on_failure=continue_on_failure,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class IPDoctestItem(pytest.Item):
|
| 281 |
+
_user_ns_orig: Dict[str, Any]
|
| 282 |
+
|
| 283 |
+
def __init__(
|
| 284 |
+
self,
|
| 285 |
+
name: str,
|
| 286 |
+
parent: "Union[IPDoctestTextfile, IPDoctestModule]",
|
| 287 |
+
runner: Optional["IPDocTestRunner"] = None,
|
| 288 |
+
dtest: Optional["doctest.DocTest"] = None,
|
| 289 |
+
) -> None:
|
| 290 |
+
super().__init__(name, parent)
|
| 291 |
+
self.runner = runner
|
| 292 |
+
self.dtest = dtest
|
| 293 |
+
self.obj = None
|
| 294 |
+
self.fixture_request: Optional[FixtureRequest] = None
|
| 295 |
+
self._user_ns_orig = {}
|
| 296 |
+
|
| 297 |
+
@classmethod
|
| 298 |
+
def from_parent( # type: ignore
|
| 299 |
+
cls,
|
| 300 |
+
parent: "Union[IPDoctestTextfile, IPDoctestModule]",
|
| 301 |
+
*,
|
| 302 |
+
name: str,
|
| 303 |
+
runner: "IPDocTestRunner",
|
| 304 |
+
dtest: "doctest.DocTest",
|
| 305 |
+
):
|
| 306 |
+
# incompatible signature due to imposed limits on subclass
|
| 307 |
+
"""The public named constructor."""
|
| 308 |
+
return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest)
|
| 309 |
+
|
| 310 |
+
def setup(self) -> None:
|
| 311 |
+
if self.dtest is not None:
|
| 312 |
+
self.fixture_request = _setup_fixtures(self)
|
| 313 |
+
globs = dict(getfixture=self.fixture_request.getfixturevalue)
|
| 314 |
+
for name, value in self.fixture_request.getfixturevalue(
|
| 315 |
+
"ipdoctest_namespace"
|
| 316 |
+
).items():
|
| 317 |
+
globs[name] = value
|
| 318 |
+
self.dtest.globs.update(globs)
|
| 319 |
+
|
| 320 |
+
from .ipdoctest import IPExample
|
| 321 |
+
|
| 322 |
+
if isinstance(self.dtest.examples[0], IPExample):
|
| 323 |
+
# for IPython examples *only*, we swap the globals with the ipython
|
| 324 |
+
# namespace, after updating it with the globals (which doctest
|
| 325 |
+
# fills with the necessary info from the module being tested).
|
| 326 |
+
self._user_ns_orig = {}
|
| 327 |
+
self._user_ns_orig.update(_ip.user_ns)
|
| 328 |
+
_ip.user_ns.update(self.dtest.globs)
|
| 329 |
+
# We must remove the _ key in the namespace, so that Python's
|
| 330 |
+
# doctest code sets it naturally
|
| 331 |
+
_ip.user_ns.pop("_", None)
|
| 332 |
+
_ip.user_ns["__builtins__"] = builtins
|
| 333 |
+
self.dtest.globs = _ip.user_ns
|
| 334 |
+
|
| 335 |
+
def teardown(self) -> None:
|
| 336 |
+
from .ipdoctest import IPExample
|
| 337 |
+
|
| 338 |
+
# Undo the test.globs reassignment we made
|
| 339 |
+
if isinstance(self.dtest.examples[0], IPExample):
|
| 340 |
+
self.dtest.globs = {}
|
| 341 |
+
_ip.user_ns.clear()
|
| 342 |
+
_ip.user_ns.update(self._user_ns_orig)
|
| 343 |
+
del self._user_ns_orig
|
| 344 |
+
|
| 345 |
+
self.dtest.globs.clear()
|
| 346 |
+
|
| 347 |
+
def runtest(self) -> None:
|
| 348 |
+
assert self.dtest is not None
|
| 349 |
+
assert self.runner is not None
|
| 350 |
+
_check_all_skipped(self.dtest)
|
| 351 |
+
self._disable_output_capturing_for_darwin()
|
| 352 |
+
failures: List["doctest.DocTestFailure"] = []
|
| 353 |
+
|
| 354 |
+
# exec(compile(..., "single", ...), ...) puts result in builtins._
|
| 355 |
+
had_underscore_value = hasattr(builtins, "_")
|
| 356 |
+
underscore_original_value = getattr(builtins, "_", None)
|
| 357 |
+
|
| 358 |
+
# Save our current directory and switch out to the one where the
|
| 359 |
+
# test was originally created, in case another doctest did a
|
| 360 |
+
# directory change. We'll restore this in the finally clause.
|
| 361 |
+
curdir = os.getcwd()
|
| 362 |
+
os.chdir(self.fspath.dirname)
|
| 363 |
+
try:
|
| 364 |
+
# Type ignored because we change the type of `out` from what
|
| 365 |
+
# ipdoctest expects.
|
| 366 |
+
self.runner.run(self.dtest, out=failures, clear_globs=False) # type: ignore[arg-type]
|
| 367 |
+
finally:
|
| 368 |
+
os.chdir(curdir)
|
| 369 |
+
if had_underscore_value:
|
| 370 |
+
setattr(builtins, "_", underscore_original_value)
|
| 371 |
+
elif hasattr(builtins, "_"):
|
| 372 |
+
delattr(builtins, "_")
|
| 373 |
+
|
| 374 |
+
if failures:
|
| 375 |
+
raise MultipleDoctestFailures(failures)
|
| 376 |
+
|
| 377 |
+
def _disable_output_capturing_for_darwin(self) -> None:
|
| 378 |
+
"""Disable output capturing. Otherwise, stdout is lost to ipdoctest (pytest#985)."""
|
| 379 |
+
if platform.system() != "Darwin":
|
| 380 |
+
return
|
| 381 |
+
capman = self.config.pluginmanager.getplugin("capturemanager")
|
| 382 |
+
if capman:
|
| 383 |
+
capman.suspend_global_capture(in_=True)
|
| 384 |
+
out, err = capman.read_global_capture()
|
| 385 |
+
sys.stdout.write(out)
|
| 386 |
+
sys.stderr.write(err)
|
| 387 |
+
|
| 388 |
+
# TODO: Type ignored -- breaks Liskov Substitution.
|
| 389 |
+
def repr_failure( # type: ignore[override]
|
| 390 |
+
self,
|
| 391 |
+
excinfo: ExceptionInfo[BaseException],
|
| 392 |
+
) -> Union[str, TerminalRepr]:
|
| 393 |
+
import doctest
|
| 394 |
+
|
| 395 |
+
failures: Optional[
|
| 396 |
+
Sequence[Union[doctest.DocTestFailure, doctest.UnexpectedException]]
|
| 397 |
+
] = None
|
| 398 |
+
if isinstance(
|
| 399 |
+
excinfo.value, (doctest.DocTestFailure, doctest.UnexpectedException)
|
| 400 |
+
):
|
| 401 |
+
failures = [excinfo.value]
|
| 402 |
+
elif isinstance(excinfo.value, MultipleDoctestFailures):
|
| 403 |
+
failures = excinfo.value.failures
|
| 404 |
+
|
| 405 |
+
if failures is None:
|
| 406 |
+
return super().repr_failure(excinfo)
|
| 407 |
+
|
| 408 |
+
reprlocation_lines = []
|
| 409 |
+
for failure in failures:
|
| 410 |
+
example = failure.example
|
| 411 |
+
test = failure.test
|
| 412 |
+
filename = test.filename
|
| 413 |
+
if test.lineno is None:
|
| 414 |
+
lineno = None
|
| 415 |
+
else:
|
| 416 |
+
lineno = test.lineno + example.lineno + 1
|
| 417 |
+
message = type(failure).__name__
|
| 418 |
+
# TODO: ReprFileLocation doesn't expect a None lineno.
|
| 419 |
+
reprlocation = ReprFileLocation(filename, lineno, message) # type: ignore[arg-type]
|
| 420 |
+
checker = _get_checker()
|
| 421 |
+
report_choice = _get_report_choice(self.config.getoption("ipdoctestreport"))
|
| 422 |
+
if lineno is not None:
|
| 423 |
+
assert failure.test.docstring is not None
|
| 424 |
+
lines = failure.test.docstring.splitlines(False)
|
| 425 |
+
# add line numbers to the left of the error message
|
| 426 |
+
assert test.lineno is not None
|
| 427 |
+
lines = [
|
| 428 |
+
"%03d %s" % (i + test.lineno + 1, x) for (i, x) in enumerate(lines)
|
| 429 |
+
]
|
| 430 |
+
# trim docstring error lines to 10
|
| 431 |
+
lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]
|
| 432 |
+
else:
|
| 433 |
+
lines = [
|
| 434 |
+
"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example"
|
| 435 |
+
]
|
| 436 |
+
indent = ">>>"
|
| 437 |
+
for line in example.source.splitlines():
|
| 438 |
+
lines.append(f"??? {indent} {line}")
|
| 439 |
+
indent = "..."
|
| 440 |
+
if isinstance(failure, doctest.DocTestFailure):
|
| 441 |
+
lines += checker.output_difference(
|
| 442 |
+
example, failure.got, report_choice
|
| 443 |
+
).split("\n")
|
| 444 |
+
else:
|
| 445 |
+
inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info)
|
| 446 |
+
lines += ["UNEXPECTED EXCEPTION: %s" % repr(inner_excinfo.value)]
|
| 447 |
+
lines += [
|
| 448 |
+
x.strip("\n") for x in traceback.format_exception(*failure.exc_info)
|
| 449 |
+
]
|
| 450 |
+
reprlocation_lines.append((reprlocation, lines))
|
| 451 |
+
return ReprFailDoctest(reprlocation_lines)
|
| 452 |
+
|
| 453 |
+
def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
|
| 454 |
+
assert self.dtest is not None
|
| 455 |
+
return self.path, self.dtest.lineno, "[ipdoctest] %s" % self.name
|
| 456 |
+
|
| 457 |
+
if pytest_version[0] < 7:
|
| 458 |
+
|
| 459 |
+
@property
|
| 460 |
+
def path(self) -> Path:
|
| 461 |
+
return Path(self.fspath)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def _get_flag_lookup() -> Dict[str, int]:
|
| 465 |
+
import doctest
|
| 466 |
+
|
| 467 |
+
return dict(
|
| 468 |
+
DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
|
| 469 |
+
DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,
|
| 470 |
+
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
|
| 471 |
+
ELLIPSIS=doctest.ELLIPSIS,
|
| 472 |
+
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
|
| 473 |
+
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
|
| 474 |
+
ALLOW_UNICODE=_get_allow_unicode_flag(),
|
| 475 |
+
ALLOW_BYTES=_get_allow_bytes_flag(),
|
| 476 |
+
NUMBER=_get_number_flag(),
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def get_optionflags(parent):
|
| 481 |
+
optionflags_str = parent.config.getini("ipdoctest_optionflags")
|
| 482 |
+
flag_lookup_table = _get_flag_lookup()
|
| 483 |
+
flag_acc = 0
|
| 484 |
+
for flag in optionflags_str:
|
| 485 |
+
flag_acc |= flag_lookup_table[flag]
|
| 486 |
+
return flag_acc
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _get_continue_on_failure(config):
|
| 490 |
+
continue_on_failure = config.getvalue("ipdoctest_continue_on_failure")
|
| 491 |
+
if continue_on_failure:
|
| 492 |
+
# We need to turn off this if we use pdb since we should stop at
|
| 493 |
+
# the first failure.
|
| 494 |
+
if config.getvalue("usepdb"):
|
| 495 |
+
continue_on_failure = False
|
| 496 |
+
return continue_on_failure
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
class IPDoctestTextfile(pytest.Module):
|
| 500 |
+
obj = None
|
| 501 |
+
|
| 502 |
+
def collect(self) -> Iterable[IPDoctestItem]:
|
| 503 |
+
import doctest
|
| 504 |
+
from .ipdoctest import IPDocTestParser
|
| 505 |
+
|
| 506 |
+
# Inspired by doctest.testfile; ideally we would use it directly,
|
| 507 |
+
# but it doesn't support passing a custom checker.
|
| 508 |
+
encoding = self.config.getini("ipdoctest_encoding")
|
| 509 |
+
text = self.path.read_text(encoding)
|
| 510 |
+
filename = str(self.path)
|
| 511 |
+
name = self.path.name
|
| 512 |
+
globs = {"__name__": "__main__"}
|
| 513 |
+
|
| 514 |
+
optionflags = get_optionflags(self)
|
| 515 |
+
|
| 516 |
+
runner = _get_runner(
|
| 517 |
+
verbose=False,
|
| 518 |
+
optionflags=optionflags,
|
| 519 |
+
checker=_get_checker(),
|
| 520 |
+
continue_on_failure=_get_continue_on_failure(self.config),
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
parser = IPDocTestParser()
|
| 524 |
+
test = parser.get_doctest(text, globs, name, filename, 0)
|
| 525 |
+
if test.examples:
|
| 526 |
+
yield IPDoctestItem.from_parent(
|
| 527 |
+
self, name=test.name, runner=runner, dtest=test
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
if pytest_version[0] < 7:
|
| 531 |
+
|
| 532 |
+
@property
|
| 533 |
+
def path(self) -> Path:
|
| 534 |
+
return Path(self.fspath)
|
| 535 |
+
|
| 536 |
+
@classmethod
|
| 537 |
+
def from_parent(
|
| 538 |
+
cls,
|
| 539 |
+
parent,
|
| 540 |
+
*,
|
| 541 |
+
fspath=None,
|
| 542 |
+
path: Optional[Path] = None,
|
| 543 |
+
**kw,
|
| 544 |
+
):
|
| 545 |
+
if path is not None:
|
| 546 |
+
import py.path
|
| 547 |
+
|
| 548 |
+
fspath = py.path.local(path)
|
| 549 |
+
return super().from_parent(parent=parent, fspath=fspath, **kw)
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def _check_all_skipped(test: "doctest.DocTest") -> None:
|
| 553 |
+
"""Raise pytest.skip() if all examples in the given DocTest have the SKIP
|
| 554 |
+
option set."""
|
| 555 |
+
import doctest
|
| 556 |
+
|
| 557 |
+
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
|
| 558 |
+
if all_skipped:
|
| 559 |
+
pytest.skip("all docstests skipped by +SKIP option")
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _is_mocked(obj: object) -> bool:
|
| 563 |
+
"""Return if an object is possibly a mock object by checking the
|
| 564 |
+
existence of a highly improbable attribute."""
|
| 565 |
+
return (
|
| 566 |
+
safe_getattr(obj, "pytest_mock_example_attribute_that_shouldnt_exist", None)
|
| 567 |
+
is not None
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
@contextmanager
|
| 572 |
+
def _patch_unwrap_mock_aware() -> Generator[None, None, None]:
|
| 573 |
+
"""Context manager which replaces ``inspect.unwrap`` with a version
|
| 574 |
+
that's aware of mock objects and doesn't recurse into them."""
|
| 575 |
+
real_unwrap = inspect.unwrap
|
| 576 |
+
|
| 577 |
+
def _mock_aware_unwrap(
|
| 578 |
+
func: Callable[..., Any], *, stop: Optional[Callable[[Any], Any]] = None
|
| 579 |
+
) -> Any:
|
| 580 |
+
try:
|
| 581 |
+
if stop is None or stop is _is_mocked:
|
| 582 |
+
return real_unwrap(func, stop=_is_mocked)
|
| 583 |
+
_stop = stop
|
| 584 |
+
return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))
|
| 585 |
+
except Exception as e:
|
| 586 |
+
warnings.warn(
|
| 587 |
+
"Got %r when unwrapping %r. This is usually caused "
|
| 588 |
+
"by a violation of Python's object protocol; see e.g. "
|
| 589 |
+
"https://github.com/pytest-dev/pytest/issues/5080" % (e, func),
|
| 590 |
+
PytestWarning,
|
| 591 |
+
)
|
| 592 |
+
raise
|
| 593 |
+
|
| 594 |
+
inspect.unwrap = _mock_aware_unwrap
|
| 595 |
+
try:
|
| 596 |
+
yield
|
| 597 |
+
finally:
|
| 598 |
+
inspect.unwrap = real_unwrap
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class IPDoctestModule(pytest.Module):
|
| 602 |
+
def collect(self) -> Iterable[IPDoctestItem]:
|
| 603 |
+
import doctest
|
| 604 |
+
from .ipdoctest import DocTestFinder, IPDocTestParser
|
| 605 |
+
|
| 606 |
+
class MockAwareDocTestFinder(DocTestFinder):
|
| 607 |
+
"""A hackish ipdoctest finder that overrides stdlib internals to fix a stdlib bug.
|
| 608 |
+
|
| 609 |
+
https://github.com/pytest-dev/pytest/issues/3456
|
| 610 |
+
https://bugs.python.org/issue25532
|
| 611 |
+
"""
|
| 612 |
+
|
| 613 |
+
def _find_lineno(self, obj, source_lines):
|
| 614 |
+
"""Doctest code does not take into account `@property`, this
|
| 615 |
+
is a hackish way to fix it. https://bugs.python.org/issue17446
|
| 616 |
+
|
| 617 |
+
Wrapped Doctests will need to be unwrapped so the correct
|
| 618 |
+
line number is returned. This will be reported upstream. #8796
|
| 619 |
+
"""
|
| 620 |
+
if isinstance(obj, property):
|
| 621 |
+
obj = getattr(obj, "fget", obj)
|
| 622 |
+
|
| 623 |
+
if hasattr(obj, "__wrapped__"):
|
| 624 |
+
# Get the main obj in case of it being wrapped
|
| 625 |
+
obj = inspect.unwrap(obj)
|
| 626 |
+
|
| 627 |
+
# Type ignored because this is a private function.
|
| 628 |
+
return super()._find_lineno( # type:ignore[misc]
|
| 629 |
+
obj,
|
| 630 |
+
source_lines,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
def _find(
|
| 634 |
+
self, tests, obj, name, module, source_lines, globs, seen
|
| 635 |
+
) -> None:
|
| 636 |
+
if _is_mocked(obj):
|
| 637 |
+
return
|
| 638 |
+
with _patch_unwrap_mock_aware():
|
| 639 |
+
# Type ignored because this is a private function.
|
| 640 |
+
super()._find( # type:ignore[misc]
|
| 641 |
+
tests, obj, name, module, source_lines, globs, seen
|
| 642 |
+
)
|
| 643 |
+
|
| 644 |
+
if self.path.name == "conftest.py":
|
| 645 |
+
if pytest_version[0] < 7:
|
| 646 |
+
module = self.config.pluginmanager._importconftest(
|
| 647 |
+
self.path,
|
| 648 |
+
self.config.getoption("importmode"),
|
| 649 |
+
)
|
| 650 |
+
else:
|
| 651 |
+
kwargs = {"rootpath": self.config.rootpath}
|
| 652 |
+
if pytest_version >= (8, 1):
|
| 653 |
+
kwargs["consider_namespace_packages"] = False
|
| 654 |
+
module = self.config.pluginmanager._importconftest(
|
| 655 |
+
self.path,
|
| 656 |
+
self.config.getoption("importmode"),
|
| 657 |
+
**kwargs,
|
| 658 |
+
)
|
| 659 |
+
else:
|
| 660 |
+
try:
|
| 661 |
+
kwargs = {"root": self.config.rootpath}
|
| 662 |
+
if pytest_version >= (8, 1):
|
| 663 |
+
kwargs["consider_namespace_packages"] = False
|
| 664 |
+
module = import_path(self.path, **kwargs)
|
| 665 |
+
except ImportError:
|
| 666 |
+
if self.config.getvalue("ipdoctest_ignore_import_errors"):
|
| 667 |
+
pytest.skip("unable to import module %r" % self.path)
|
| 668 |
+
else:
|
| 669 |
+
raise
|
| 670 |
+
# Uses internal doctest module parsing mechanism.
|
| 671 |
+
finder = MockAwareDocTestFinder(parser=IPDocTestParser())
|
| 672 |
+
optionflags = get_optionflags(self)
|
| 673 |
+
runner = _get_runner(
|
| 674 |
+
verbose=False,
|
| 675 |
+
optionflags=optionflags,
|
| 676 |
+
checker=_get_checker(),
|
| 677 |
+
continue_on_failure=_get_continue_on_failure(self.config),
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
for test in finder.find(module, module.__name__):
|
| 681 |
+
if test.examples: # skip empty ipdoctests
|
| 682 |
+
yield IPDoctestItem.from_parent(
|
| 683 |
+
self, name=test.name, runner=runner, dtest=test
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
if pytest_version[0] < 7:
|
| 687 |
+
|
| 688 |
+
@property
|
| 689 |
+
def path(self) -> Path:
|
| 690 |
+
return Path(self.fspath)
|
| 691 |
+
|
| 692 |
+
@classmethod
|
| 693 |
+
def from_parent(
|
| 694 |
+
cls,
|
| 695 |
+
parent,
|
| 696 |
+
*,
|
| 697 |
+
fspath=None,
|
| 698 |
+
path: Optional[Path] = None,
|
| 699 |
+
**kw,
|
| 700 |
+
):
|
| 701 |
+
if path is not None:
|
| 702 |
+
import py.path
|
| 703 |
+
|
| 704 |
+
fspath = py.path.local(path)
|
| 705 |
+
return super().from_parent(parent=parent, fspath=fspath, **kw)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def _setup_fixtures(doctest_item: IPDoctestItem) -> FixtureRequest:
|
| 709 |
+
"""Used by IPDoctestTextfile and IPDoctestItem to setup fixture information."""
|
| 710 |
+
|
| 711 |
+
def func() -> None:
|
| 712 |
+
pass
|
| 713 |
+
|
| 714 |
+
doctest_item.funcargs = {} # type: ignore[attr-defined]
|
| 715 |
+
fm = doctest_item.session._fixturemanager
|
| 716 |
+
kwargs = {"node": doctest_item, "func": func, "cls": None}
|
| 717 |
+
if pytest_version <= (8, 0):
|
| 718 |
+
kwargs["funcargs"] = False
|
| 719 |
+
doctest_item._fixtureinfo = fm.getfixtureinfo( # type: ignore[attr-defined]
|
| 720 |
+
**kwargs
|
| 721 |
+
)
|
| 722 |
+
fixture_request = FixtureRequest(doctest_item, _ispytest=True)
|
| 723 |
+
if pytest_version <= (8, 0):
|
| 724 |
+
fixture_request._fillfixtures()
|
| 725 |
+
return fixture_request
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def _init_checker_class() -> Type["IPDoctestOutputChecker"]:
|
| 729 |
+
import doctest
|
| 730 |
+
import re
|
| 731 |
+
from .ipdoctest import IPDoctestOutputChecker
|
| 732 |
+
|
| 733 |
+
class LiteralsOutputChecker(IPDoctestOutputChecker):
|
| 734 |
+
# Based on doctest_nose_plugin.py from the nltk project
|
| 735 |
+
# (https://github.com/nltk/nltk) and on the "numtest" doctest extension
|
| 736 |
+
# by Sebastien Boisgerault (https://github.com/boisgera/numtest).
|
| 737 |
+
|
| 738 |
+
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
|
| 739 |
+
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
|
| 740 |
+
_number_re = re.compile(
|
| 741 |
+
r"""
|
| 742 |
+
(?P<number>
|
| 743 |
+
(?P<mantissa>
|
| 744 |
+
(?P<integer1> [+-]?\d*)\.(?P<fraction>\d+)
|
| 745 |
+
|
|
| 746 |
+
(?P<integer2> [+-]?\d+)\.
|
| 747 |
+
)
|
| 748 |
+
(?:
|
| 749 |
+
[Ee]
|
| 750 |
+
(?P<exponent1> [+-]?\d+)
|
| 751 |
+
)?
|
| 752 |
+
|
|
| 753 |
+
(?P<integer3> [+-]?\d+)
|
| 754 |
+
(?:
|
| 755 |
+
[Ee]
|
| 756 |
+
(?P<exponent2> [+-]?\d+)
|
| 757 |
+
)
|
| 758 |
+
)
|
| 759 |
+
""",
|
| 760 |
+
re.VERBOSE,
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
def check_output(self, want: str, got: str, optionflags: int) -> bool:
|
| 764 |
+
if super().check_output(want, got, optionflags):
|
| 765 |
+
return True
|
| 766 |
+
|
| 767 |
+
allow_unicode = optionflags & _get_allow_unicode_flag()
|
| 768 |
+
allow_bytes = optionflags & _get_allow_bytes_flag()
|
| 769 |
+
allow_number = optionflags & _get_number_flag()
|
| 770 |
+
|
| 771 |
+
if not allow_unicode and not allow_bytes and not allow_number:
|
| 772 |
+
return False
|
| 773 |
+
|
| 774 |
+
def remove_prefixes(regex: Pattern[str], txt: str) -> str:
|
| 775 |
+
return re.sub(regex, r"\1\2", txt)
|
| 776 |
+
|
| 777 |
+
if allow_unicode:
|
| 778 |
+
want = remove_prefixes(self._unicode_literal_re, want)
|
| 779 |
+
got = remove_prefixes(self._unicode_literal_re, got)
|
| 780 |
+
|
| 781 |
+
if allow_bytes:
|
| 782 |
+
want = remove_prefixes(self._bytes_literal_re, want)
|
| 783 |
+
got = remove_prefixes(self._bytes_literal_re, got)
|
| 784 |
+
|
| 785 |
+
if allow_number:
|
| 786 |
+
got = self._remove_unwanted_precision(want, got)
|
| 787 |
+
|
| 788 |
+
return super().check_output(want, got, optionflags)
|
| 789 |
+
|
| 790 |
+
def _remove_unwanted_precision(self, want: str, got: str) -> str:
|
| 791 |
+
wants = list(self._number_re.finditer(want))
|
| 792 |
+
gots = list(self._number_re.finditer(got))
|
| 793 |
+
if len(wants) != len(gots):
|
| 794 |
+
return got
|
| 795 |
+
offset = 0
|
| 796 |
+
for w, g in zip(wants, gots):
|
| 797 |
+
fraction: Optional[str] = w.group("fraction")
|
| 798 |
+
exponent: Optional[str] = w.group("exponent1")
|
| 799 |
+
if exponent is None:
|
| 800 |
+
exponent = w.group("exponent2")
|
| 801 |
+
precision = 0 if fraction is None else len(fraction)
|
| 802 |
+
if exponent is not None:
|
| 803 |
+
precision -= int(exponent)
|
| 804 |
+
if float(w.group()) == approx(float(g.group()), abs=10**-precision):
|
| 805 |
+
# They're close enough. Replace the text we actually
|
| 806 |
+
# got with the text we want, so that it will match when we
|
| 807 |
+
# check the string literally.
|
| 808 |
+
got = (
|
| 809 |
+
got[: g.start() + offset] + w.group() + got[g.end() + offset :]
|
| 810 |
+
)
|
| 811 |
+
offset += w.end() - w.start() - (g.end() - g.start())
|
| 812 |
+
return got
|
| 813 |
+
|
| 814 |
+
return LiteralsOutputChecker
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
def _get_checker() -> "IPDoctestOutputChecker":
|
| 818 |
+
"""Return a IPDoctestOutputChecker subclass that supports some
|
| 819 |
+
additional options:
|
| 820 |
+
|
| 821 |
+
* ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''
|
| 822 |
+
prefixes (respectively) in string literals. Useful when the same
|
| 823 |
+
ipdoctest should run in Python 2 and Python 3.
|
| 824 |
+
|
| 825 |
+
* NUMBER to ignore floating-point differences smaller than the
|
| 826 |
+
precision of the literal number in the ipdoctest.
|
| 827 |
+
|
| 828 |
+
An inner class is used to avoid importing "ipdoctest" at the module
|
| 829 |
+
level.
|
| 830 |
+
"""
|
| 831 |
+
global CHECKER_CLASS
|
| 832 |
+
if CHECKER_CLASS is None:
|
| 833 |
+
CHECKER_CLASS = _init_checker_class()
|
| 834 |
+
return CHECKER_CLASS()
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
def _get_allow_unicode_flag() -> int:
|
| 838 |
+
"""Register and return the ALLOW_UNICODE flag."""
|
| 839 |
+
import doctest
|
| 840 |
+
|
| 841 |
+
return doctest.register_optionflag("ALLOW_UNICODE")
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
def _get_allow_bytes_flag() -> int:
|
| 845 |
+
"""Register and return the ALLOW_BYTES flag."""
|
| 846 |
+
import doctest
|
| 847 |
+
|
| 848 |
+
return doctest.register_optionflag("ALLOW_BYTES")
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def _get_number_flag() -> int:
|
| 852 |
+
"""Register and return the NUMBER flag."""
|
| 853 |
+
import doctest
|
| 854 |
+
|
| 855 |
+
return doctest.register_optionflag("NUMBER")
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
def _get_report_choice(key: str) -> int:
|
| 859 |
+
"""Return the actual `ipdoctest` module flag value.
|
| 860 |
+
|
| 861 |
+
We want to do it as late as possible to avoid importing `ipdoctest` and all
|
| 862 |
+
its dependencies when parsing options, as it adds overhead and breaks tests.
|
| 863 |
+
"""
|
| 864 |
+
import doctest
|
| 865 |
+
|
| 866 |
+
return {
|
| 867 |
+
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
|
| 868 |
+
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
|
| 869 |
+
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
|
| 870 |
+
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
|
| 871 |
+
DOCTEST_REPORT_CHOICE_NONE: 0,
|
| 872 |
+
}[key]
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
@pytest.fixture(scope="session")
|
| 876 |
+
def ipdoctest_namespace() -> Dict[str, Any]:
|
| 877 |
+
"""Fixture that returns a :py:class:`dict` that will be injected into the
|
| 878 |
+
namespace of ipdoctests."""
|
| 879 |
+
return dict()
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/setup.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""A Nose plugin to support IPython doctests.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from setuptools import setup
|
| 6 |
+
|
| 7 |
+
setup(name='IPython doctest plugin',
|
| 8 |
+
version='0.1',
|
| 9 |
+
author='The IPython Team',
|
| 10 |
+
description = 'Nose plugin to load IPython-extended doctests',
|
| 11 |
+
license = 'LGPL',
|
| 12 |
+
py_modules = ['ipdoctest'],
|
| 13 |
+
entry_points = {
|
| 14 |
+
'nose.plugins.0.10': ['ipdoctest = ipdoctest:IPythonDoctest',
|
| 15 |
+
'extdoctest = ipdoctest:ExtensionDoctest',
|
| 16 |
+
],
|
| 17 |
+
},
|
| 18 |
+
)
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simple.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simple example using doctests.
|
| 2 |
+
|
| 3 |
+
This file just contains doctests both using plain python and IPython prompts.
|
| 4 |
+
All tests should be loaded by Pytest.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
def pyfunc():
|
| 8 |
+
"""Some pure python tests...
|
| 9 |
+
|
| 10 |
+
>>> pyfunc()
|
| 11 |
+
'pyfunc'
|
| 12 |
+
|
| 13 |
+
>>> import os
|
| 14 |
+
|
| 15 |
+
>>> 2+3
|
| 16 |
+
5
|
| 17 |
+
|
| 18 |
+
>>> for i in range(3):
|
| 19 |
+
... print(i, end=' ')
|
| 20 |
+
... print(i+1, end=' ')
|
| 21 |
+
...
|
| 22 |
+
0 1 1 2 2 3
|
| 23 |
+
"""
|
| 24 |
+
return 'pyfunc'
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def ipyfunc():
|
| 28 |
+
"""Some IPython tests...
|
| 29 |
+
|
| 30 |
+
In [1]: ipyfunc()
|
| 31 |
+
Out[1]: 'ipyfunc'
|
| 32 |
+
|
| 33 |
+
In [2]: import os
|
| 34 |
+
|
| 35 |
+
In [3]: 2+3
|
| 36 |
+
Out[3]: 5
|
| 37 |
+
|
| 38 |
+
In [4]: for i in range(3):
|
| 39 |
+
...: print(i, end=' ')
|
| 40 |
+
...: print(i+1, end=' ')
|
| 41 |
+
...:
|
| 42 |
+
Out[4]: 0 1 1 2 2 3
|
| 43 |
+
"""
|
| 44 |
+
return "ipyfunc"
|
material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/testing/plugin/simplevars.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
x = 1
|
| 2 |
+
print("x is:", x)
|