-
-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: add parameter to for output stream #235
Open
bpshaver
wants to merge
5
commits into
pavdmyt:master
Choose a base branch
from
bpshaver:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4e00fcd
feat: add parameter to for output stream
bpshaver c2fd566
chore(fmt): formatting code
bpshaver 87a0b8e
fix: changed default value of `stream` param to `None`
bpshaver eaec3c9
chore(fmt): yet another auto-format
bpshaver 2569f15
test: fixed failing test_in_out.py::test_hide_show due to teeardown f…
bpshaver File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,6 +28,7 @@ | |
Iterator, | ||
Optional, | ||
Sequence, | ||
TextIO, | ||
Type, | ||
TypeVar, | ||
Union, | ||
|
@@ -89,8 +90,8 @@ def fancy_handler(signum: int, frame: Any, spinner: Yaspin) -> None: # pylint: | |
|
||
class Yaspin: # pylint: disable=too-many-instance-attributes | ||
"""Implements a context manager that spawns a thread | ||
to write spinner frames into a tty (stdout) during | ||
context execution. | ||
to write spinner frames into a tty (stdout by default) | ||
during context execution. | ||
""" | ||
|
||
# When Python finds its output attached to a terminal, | ||
|
@@ -108,13 +109,17 @@ def __init__( # pylint: disable=too-many-arguments | |
side: str = "left", | ||
sigmap: Optional[dict[signal.Signals, SignalHandlers]] = None, | ||
timer: bool = False, | ||
stream: TextIO = sys.stdout | ||
) -> None: | ||
# Stream | ||
self._stream = stream | ||
self._stream_lock = threading.Lock() | ||
|
||
# Spinner | ||
self._spinner = self._set_spinner(spinner) | ||
self._frames = self._set_frames(self._spinner, reversal) | ||
self._interval = self._set_interval(self._spinner) | ||
self._cycle = self._set_cycle(self._frames) | ||
|
||
# Color Specification | ||
self._color = self._set_color(color) if color else color | ||
self._on_color = self._set_on_color(on_color) if on_color else on_color | ||
|
@@ -134,7 +139,6 @@ def __init__( # pylint: disable=too-many-arguments | |
self._hide_spin: Optional[threading.Event] = None | ||
self._spin_thread: Optional[threading.Thread] = None | ||
self._last_frame: Optional[str] = None | ||
self._stdout_lock = threading.Lock() | ||
self._hidden_level = 0 | ||
self._cur_line_len = 0 | ||
|
||
|
@@ -144,6 +148,7 @@ def __init__( # pylint: disable=too-many-arguments | |
# custom handlers set by ``sigmap`` at the cleanup phase. | ||
self._dfl_sigmap: dict[signal.Signals, SignalHandlers] = {} | ||
|
||
|
||
# Dunders | ||
# | ||
def __repr__(self) -> str: | ||
|
@@ -316,14 +321,14 @@ def hide(self) -> None: | |
raise RuntimeError("hide_spin is None") | ||
|
||
if thr_is_alive and not self._hide_spin.is_set(): | ||
with self._stdout_lock: | ||
with self._stream_lock: | ||
# set the hidden spinner flag | ||
self._hide_spin.set() | ||
self._clear_line() | ||
|
||
# flush the stdout buffer so the current line | ||
# flush the stream buffer so the current line | ||
# can be rewritten to | ||
sys.stdout.flush() | ||
self._stream.flush() | ||
|
||
@contextmanager | ||
def hidden(self) -> Generator[None, None, None]: | ||
|
@@ -345,7 +350,7 @@ def show(self) -> None: | |
raise RuntimeError("hide_spin is None") | ||
|
||
if thr_is_alive and self._hide_spin.is_set(): | ||
with self._stdout_lock: | ||
with self._stream_lock: | ||
# clear the hidden spinner flag | ||
self._hide_spin.clear() | ||
# clear the current line so the spinner is not appended to it | ||
|
@@ -355,13 +360,13 @@ def write(self, text: str) -> None: | |
"""Write text in the terminal without breaking the spinner.""" | ||
# similar to tqdm.write() | ||
# https://pypi.python.org/pypi/tqdm#writing-messages | ||
with self._stdout_lock: | ||
with self._stream_lock: | ||
self._clear_line() | ||
if isinstance(text, (str, bytes)): | ||
_text = to_unicode(text) | ||
else: | ||
_text = str(text) | ||
sys.stdout.write(f"{_text}\n") | ||
self._stream.write(f"{_text}\n") | ||
self._cur_line_len = 0 | ||
|
||
def ok(self, text: str = "OK") -> None: | ||
|
@@ -374,15 +379,11 @@ def fail(self, text: str = "FAIL") -> None: | |
_text = text if text else "FAIL" | ||
self._freeze(_text) | ||
|
||
def is_jupyter(self) -> bool: | ||
return not self._stream.isatty() | ||
|
||
# Protected | ||
# | ||
@staticmethod | ||
def _warn_color_disabled() -> None: | ||
warnings.warn( | ||
"color, on_color and attrs are not supported when running in jupyter", | ||
stacklevel=3, | ||
) | ||
|
||
def _freeze(self, final_text: str) -> None: | ||
"""Stop spinner, compose last frame and 'freeze' it.""" | ||
text = to_unicode(final_text) | ||
|
@@ -391,10 +392,10 @@ def _freeze(self, final_text: str) -> None: | |
# Should be stopped here, otherwise prints after | ||
# self._freeze call will mess up the spinner | ||
self.stop() | ||
with self._stdout_lock: | ||
with self._stream_lock: | ||
if self._last_frame is None: | ||
raise RuntimeError("last_frame is None") | ||
sys.stdout.write(self._last_frame) | ||
self._stream.write(self._last_frame) | ||
self._cur_line_len = 0 | ||
|
||
def _spin(self) -> None: | ||
|
@@ -412,10 +413,10 @@ def _spin(self) -> None: | |
out = self._compose_out(spin_phase) | ||
|
||
# Write | ||
with self._stdout_lock: | ||
with self._stream_lock: | ||
self._clear_line() | ||
sys.stdout.write(out) | ||
sys.stdout.flush() | ||
self._stream.write(out) | ||
self._stream.flush() | ||
self._cur_line_len = max(self._cur_line_len, len(out)) | ||
|
||
# Wait | ||
|
@@ -489,15 +490,28 @@ def _reset_signal_handlers(self) -> None: | |
for sig, sig_handler in self._dfl_sigmap.items(): | ||
signal.signal(sig, sig_handler) | ||
|
||
# Static | ||
# | ||
@staticmethod | ||
def is_jupyter() -> bool: | ||
return not sys.stdout.isatty() | ||
def _hide_cursor(self) -> None: | ||
if self._stream.isatty(): | ||
# ANSI Control Sequence DECTCEM 1 does not work in Jupyter | ||
self._stream.write("\033[?25l") | ||
self._stream.flush() | ||
|
||
@staticmethod | ||
def _set_color(value: str) -> str: | ||
if Yaspin.is_jupyter(): | ||
def _show_cursor(self) -> None: | ||
if self._stream.isatty(): | ||
# ANSI Control Sequence DECTCEM 2 does not work in Jupyter | ||
self._stream.write("\033[?25h") | ||
self._stream.flush() | ||
|
||
def _clear_line(self) -> None: | ||
if self._stream.isatty(): | ||
# ANSI Control Sequence EL does not work in Jupyter | ||
self._stream.write("\r\033[K") | ||
else: | ||
fill = " " * self._cur_line_len | ||
self._stream.write(f"\r{fill}\r") | ||
|
||
def _set_color(self, value: str) -> str: | ||
if self.is_jupyter(): | ||
Yaspin._warn_color_disabled() | ||
|
||
if value not in COLORS: | ||
|
@@ -508,9 +522,8 @@ def _set_color(value: str) -> str: | |
) | ||
return value | ||
|
||
@staticmethod | ||
def _set_on_color(value: str) -> str: | ||
if Yaspin.is_jupyter(): | ||
def _set_on_color(self, value: str) -> str: | ||
if self.is_jupyter(): | ||
Yaspin._warn_color_disabled() | ||
|
||
if value not in HIGHLIGHTS: | ||
|
@@ -520,9 +533,8 @@ def _set_on_color(value: str) -> str: | |
) | ||
return value | ||
|
||
@staticmethod | ||
def _set_attrs(attrs: Sequence[str]) -> set[str]: | ||
if Yaspin.is_jupyter(): | ||
def _set_attrs(self, attrs: Sequence[str]) -> set[str]: | ||
if self.is_jupyter(): | ||
Yaspin._warn_color_disabled() | ||
|
||
for attr in attrs: | ||
|
@@ -533,6 +545,15 @@ def _set_attrs(attrs: Sequence[str]) -> set[str]: | |
) | ||
return set(attrs) | ||
|
||
# Static | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What is the purpose of this comment? |
||
# | ||
@staticmethod | ||
def _warn_color_disabled() -> None: | ||
warnings.warn( | ||
"color, on_color and attrs are not supported when running in jupyter", | ||
stacklevel=3, | ||
) | ||
|
||
@staticmethod | ||
def _set_spinner(spinner: Spinner) -> Spinner: | ||
if hasattr(spinner, "frames") and hasattr(spinner, "interval"): | ||
|
@@ -591,24 +612,3 @@ def _set_interval(spinner: Spinner) -> float: | |
def _set_cycle(frames: Union[str, Sequence[str]]) -> Iterator[str]: | ||
return itertools.cycle(frames) | ||
|
||
@staticmethod | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because of calls so |
||
def _hide_cursor() -> None: | ||
if sys.stdout.isatty(): | ||
# ANSI Control Sequence DECTCEM 1 does not work in Jupyter | ||
sys.stdout.write("\033[?25l") | ||
sys.stdout.flush() | ||
|
||
@staticmethod | ||
def _show_cursor() -> None: | ||
if sys.stdout.isatty(): | ||
# ANSI Control Sequence DECTCEM 2 does not work in Jupyter | ||
sys.stdout.write("\033[?25h") | ||
sys.stdout.flush() | ||
|
||
def _clear_line(self) -> None: | ||
if sys.stdout.isatty(): | ||
# ANSI Control Sequence EL does not work in Jupyter | ||
sys.stdout.write("\r\033[K") | ||
else: | ||
fill = " " * self._cur_line_len | ||
sys.stdout.write(f"\r{fill}\r") |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am pretty sure that Jupyter is not the only front-end capable of intercepting the output stream.