From 698b12e1c95a517e714141aeed873c3eb45cb784 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Mon, 16 Nov 2026 22:00:45 -0800 Subject: [PATCH 1/4] Restore caller output streams after CLI conversion Refactor output stream handling to use try-finally for restoration. --- pypinyin/runner.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pypinyin/runner.py b/pypinyin/runner.py index 208903fe..bc4f3686 100644 --- a/pypinyin/runner.py +++ b/pypinyin/runner.py @@ -122,11 +122,12 @@ def main(): # 重设标准输出流和标准错误流 # 不输出任何字符,防止污染命令行命令的输出结果 # 其实主要是为了干掉 jieba 内的 print 语句 ;) - sys.stdout = sys.stderr = NullWriter() - results = [func(han, style=style, **kwargs) for han in hans] - # 恢复默认 - sys.stdout = sys.__stdout__ - sys.stderr = sys.__stderr__ + stdout, stderr = sys.stdout, sys.stderr + try: + sys.stdout = sys.stderr = NullWriter() + results = [func(han, style=style, **kwargs) for han in hans] + finally: + sys.stdout, sys.stderr = stdout, stderr for result in results: if not result: From 60ead97710a3edf8fc782143638779581f479996 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Mon, 16 Nov 2026 22:01:08 -0800 Subject: [PATCH 2/4] Test exact stream and exception restoration on success and failure Added tests for runner functionality and error handling. --- tests/test_cmd.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/tests/test_cmd.py b/tests/test_cmd.py index 4ed46770..2e1c0b92 100644 --- a/tests/test_cmd.py +++ b/tests/test_cmd.py @@ -4,10 +4,12 @@ from __future__ import unicode_literals import sys +import io +import logging from pypinyin.compat import SUPPORT_UCS4 from pypinyin import runner from pypinyin.tools import toneconvert -from pytest import mark +from pytest import mark, raises class Buffer(object): @@ -40,6 +42,55 @@ def test_runner_custom(): assert options.hans == ['你好啊'] +@mark.parametrize('func_name,expected', [ + ('pinyin', 'nǐ hǎo\n'), + ('slug', 'nǐ-hǎo\n'), +]) +def test_runner_restores_redirected_streams(monkeypatch, func_name, expected): + stdout, stderr = io.StringIO(), io.StringIO() + monkeypatch.setattr(sys, 'stdin', io.StringIO('')) + monkeypatch.setattr(sys, 'stdout', stdout) + monkeypatch.setattr(sys, 'stderr', stderr) + monkeypatch.setattr(sys, 'argv', ['pypinyin', '-f', func_name, '你好']) + previous_disable = logging.root.manager.disable + try: + runner.main() + assert sys.stdout is stdout + assert sys.stderr is stderr + assert stdout.getvalue() == expected + assert stderr.getvalue() == '' + finally: + logging.disable(previous_disable) + + +@mark.parametrize('error_type', [ValueError, KeyboardInterrupt]) +def test_runner_restores_streams_on_conversion_error(monkeypatch, error_type): + stdout, stderr = io.StringIO(), io.StringIO() + monkeypatch.setattr(sys, 'stdin', io.StringIO('')) + monkeypatch.setattr(sys, 'stdout', stdout) + monkeypatch.setattr(sys, 'stderr', stderr) + monkeypatch.setattr(sys, 'argv', ['pypinyin', '你好']) + error = error_type('conversion failed') + + def pinyin(*args, **kwargs): + print('converter noise') + sys.stderr.write('converter diagnostic') + raise error + + monkeypatch.setattr(runner.pypinyin, 'pinyin', pinyin) + previous_disable = logging.root.manager.disable + try: + with raises(error_type) as caught: + runner.main() + assert caught.value is error + assert sys.stdout is stdout + assert sys.stderr is stderr + assert stdout.getvalue() == '' + assert stderr.getvalue() == '' + finally: + logging.disable(previous_disable) + + @mark.parametrize('args,output', [ [['to-normal', 'yí,yì'], ['yi,yi', '\n']], [['to-tone', 'yi2,yi4'], ['yí,yì', '\n']], From 1001912a0e456590a9021a912a2f9dfab9330b4a Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Mon, 16 Nov 2026 22:01:34 -0800 Subject: [PATCH 3/4] Document CLI output stream restoration fix Added a new entry for the unreleased changes and fixed the output streams restoration note. --- CHANGELOG.rst | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 085ed728..1306f8d7 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,11 @@ Changelog --------- +Unreleased +++++++++++ + +* **[Fixed]** Restore the caller's output streams after CLI conversion, including when conversion raises an exception. + Unreleased ++++++++++ From 24a1e74323f12079c824ca585b0b0f061d5566ed Mon Sep 17 00:00:00 2001 From: mozillazg Date: Sun, 22 Nov 2026 21:26:15 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E8=A7=A3=E5=86=B3=20review=20=E6=84=8F?= =?UTF-8?q?=E8=A7=81=EF=BC=9A=E6=81=A2=E5=A4=8D=20logging=20=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=B9=B6=E5=8A=A0=E5=9B=BA=20CLI=20=E6=B5=81=E6=81=A2?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - main() 结束后恢复调用者的 logging 禁用级别(之前会永久关闭 CRITICAL 以下日志) - NullWriter 增加 flush()/isatty(),避免被静默的第三方库调用时 AttributeError - 注释说明必须恢复调用者安装的流而不能再写回 sys.__stdout__/__stderr__ - CHANGELOG 条目并入已有的 Unreleased 段并改为中文,补充 #384 链接 - 测试用 fixture 消除重复的 setup,并断言 logging 状态被恢复 --- CHANGELOG.rst | 10 +++---- pypinyin/runner.py | 17 ++++++++++- tests/test_cmd.py | 70 ++++++++++++++++++++++++++-------------------- 3 files changed, 61 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 1306f8d7..41cd84fc 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,11 +1,6 @@ Changelog --------- -Unreleased -++++++++++ - -* **[Fixed]** Restore the caller's output streams after CLI conversion, including when conversion raises an exception. - Unreleased ++++++++++ @@ -16,6 +11,10 @@ Unreleased * **[Fixed]** 修复 ``Style.WADEGILES`` 转换表中恒等映射(源和目标相同)被跳过的问题, 例如 ``火车`` 现在正确输出 ``huo ch'e`` 、 ``说`` 输出 ``shuo`` (之前输出 ``ho`` 、 ``sho`` )。 +* **[Fixed]** 修复命令行工具在转换过程中替换 ``sys.stdout``/``sys.stderr`` 后 + 不恢复调用者数据流的问题:成功时改为恢复调用者安装的流(之前恢复的是 + ``sys.__stdout__``),转换抛出异常时也会恢复,避免 traceback 等后续输出被吞掉; + 同时恢复调用者的 logging 级别。 via `#384`_ `0.55.0`_ (2025-07-20) @@ -1090,6 +1089,7 @@ __ https://github.com/mozillazg/python-pinyin/issues/8 .. _#329: https://github.com/mozillazg/python-pinyin/pull/329 .. _#343: https://github.com/mozillazg/python-pinyin/pull/343 .. _#348: https://github.com/mozillazg/python-pinyin/pull/348 +.. _#384: https://github.com/mozillazg/python-pinyin/pull/384 .. _@hanabi1224: https://github.com/hanabi1224 .. _@yangwe1: https://github.com/yangwe1 .. _@Freed-Wu: https://github.com/Freed-Wu diff --git a/pypinyin/runner.py b/pypinyin/runner.py index bc4f3686..d2459e78 100644 --- a/pypinyin/runner.py +++ b/pypinyin/runner.py @@ -47,6 +47,12 @@ class NullWriter(object): def write(self, string): pass + def flush(self): + pass + + def isatty(self): + return False + def get_parser(): parser = ArgumentParser(description='convert chinese to pinyin.') @@ -82,9 +88,16 @@ def get_parser(): def main(): - # 禁用除 CRITICAL 外的日志消息 + # 禁用除 CRITICAL 外的日志消息,结束后恢复调用者原有的日志级别 + previous_disable = logging.root.manager.disable logging.disable(logging.CRITICAL) + try: + _run() + finally: + logging.disable(previous_disable) + +def _run(): # read hans from stdin if not sys.stdin.isatty(): pipe_data = sys.stdin.read().strip() @@ -122,6 +135,8 @@ def main(): # 重设标准输出流和标准错误流 # 不输出任何字符,防止污染命令行命令的输出结果 # 其实主要是为了干掉 jieba 内的 print 语句 ;) + # 注意:结束后要恢复调用者安装的流,而不是 sys.__stdout__/sys.__stderr__, + # 否则调用者自己的输出重定向会失效,且异常时会把后续输出全部吞掉 stdout, stderr = sys.stdout, sys.stderr try: sys.stdout = sys.stderr = NullWriter() diff --git a/tests/test_cmd.py b/tests/test_cmd.py index 2e1c0b92..ee9f64f7 100644 --- a/tests/test_cmd.py +++ b/tests/test_cmd.py @@ -3,13 +3,13 @@ from __future__ import unicode_literals -import sys import io import logging +import sys from pypinyin.compat import SUPPORT_UCS4 from pypinyin import runner from pypinyin.tools import toneconvert -from pytest import mark, raises +from pytest import fixture, mark, raises class Buffer(object): @@ -42,34 +42,45 @@ def test_runner_custom(): assert options.hans == ['你好啊'] -@mark.parametrize('func_name,expected', [ - ('pinyin', 'nǐ hǎo\n'), - ('slug', 'nǐ-hǎo\n'), -]) -def test_runner_restores_redirected_streams(monkeypatch, func_name, expected): +@fixture +def redirected(monkeypatch): + """把标准输入输出重定向到调用者自己的流。""" stdout, stderr = io.StringIO(), io.StringIO() monkeypatch.setattr(sys, 'stdin', io.StringIO('')) monkeypatch.setattr(sys, 'stdout', stdout) monkeypatch.setattr(sys, 'stderr', stderr) - monkeypatch.setattr(sys, 'argv', ['pypinyin', '-f', func_name, '你好']) + monkeypatch.setattr(sys, 'argv', ['pypinyin', '你好']) previous_disable = logging.root.manager.disable try: - runner.main() - assert sys.stdout is stdout - assert sys.stderr is stderr - assert stdout.getvalue() == expected - assert stderr.getvalue() == '' + yield stdout, stderr finally: logging.disable(previous_disable) +@mark.parametrize('func_name,expected', [ + ('pinyin', 'nǐ hǎo\n'), + ('slug', 'nǐ-hǎo\n'), +]) +def test_runner_restores_redirected_streams(redirected, monkeypatch, + func_name, expected): + stdout, stderr = redirected + previous_disable = logging.root.manager.disable + monkeypatch.setattr(sys, 'argv', ['pypinyin', '-f', func_name, '你好']) + + runner.main() + + assert sys.stdout is stdout + assert sys.stderr is stderr + assert stdout.getvalue() == expected + assert stderr.getvalue() == '' + assert logging.root.manager.disable == previous_disable + + @mark.parametrize('error_type', [ValueError, KeyboardInterrupt]) -def test_runner_restores_streams_on_conversion_error(monkeypatch, error_type): - stdout, stderr = io.StringIO(), io.StringIO() - monkeypatch.setattr(sys, 'stdin', io.StringIO('')) - monkeypatch.setattr(sys, 'stdout', stdout) - monkeypatch.setattr(sys, 'stderr', stderr) - monkeypatch.setattr(sys, 'argv', ['pypinyin', '你好']) +def test_runner_restores_streams_on_error(redirected, monkeypatch, + error_type): + stdout, stderr = redirected + previous_disable = logging.root.manager.disable error = error_type('conversion failed') def pinyin(*args, **kwargs): @@ -78,17 +89,16 @@ def pinyin(*args, **kwargs): raise error monkeypatch.setattr(runner.pypinyin, 'pinyin', pinyin) - previous_disable = logging.root.manager.disable - try: - with raises(error_type) as caught: - runner.main() - assert caught.value is error - assert sys.stdout is stdout - assert sys.stderr is stderr - assert stdout.getvalue() == '' - assert stderr.getvalue() == '' - finally: - logging.disable(previous_disable) + + with raises(error_type) as caught: + runner.main() + + assert caught.value is error + assert sys.stdout is stdout + assert sys.stderr is stderr + assert stdout.getvalue() == '' + assert stderr.getvalue() == '' + assert logging.root.manager.disable == previous_disable @mark.parametrize('args,output', [