2017-12-18 8 views
1

저는 파이썬 REPL에서 모든 출력을 무시하고 파싱 할 방법을 찾고 있습니다 : 예를 들어 터미널에있는 python/IPython, qtconsole.REPL 출력을 무시하십시오.

인쇄 기능을 재정 의하여 인쇄 된 텍스트에 대해 간단합니다. 사소한 예를 들어, 우리는 모든 출력에 느낌표를 추가하고 싶은 말 :

orig_print = print 
print = lambda text: orig_print(text + '!') 

지금 모든 인쇄 명령이 추가 된 느낌표가있을 것이다. 다음과 같이 재설정 할 수 있습니다.

del print 

내 질문 : 어떻게 REPL 출력에 해당하는 작업을 수행합니까? 예를 들어, 어떻게하면 이것이 작동할까요?

In[1]: 5 + 5 
Out[2]: 10! 

검색은 contextlib, 하위 프로세스 및 sys.stdout의 경로 아래로 나를 인도했다,하지만 난 해결책을 찾기 위해 아직했습니다. Github에서 sympy의 인쇄 모듈을 검사했지만 성공하지 못했습니다.

+0

흠 .. 어쩌면 이것은 그것은''다음 줄에 변경 될'TMP (텍스트를 수정하는 것이 가능 –

답변

2

방금 ​​sys.stdout.write을 덮어 쓰려고했는데 몇 가지 단점이 있습니다. 내가 틀렸다면 누군가가 나를 교정 할 것이지만 나는 이것보다 훨씬 좋아질 것이라고 생각하지 않습니다.

In [1]: import sys 

In [2]: tmp = sys.stdout.write 

In [3]: sys.stdout.write = lambda text: tmp(text + '!') 

In [4]: 5 + 5 
!Out[4]: 10! 
!! 
!!In [5]: 

편집 :
내가 여기까지 왔. 1 여분의 !이 어디서 왔는지 알아 내지 못했습니까?

In [5]: sys.stdout.write = lambda text: tmp(text if text.endswith('\n') else text + '!\r') 

In [6]: 5+5 
Out[6]: 10! 
! 
In [7]: 
+0

을 sys.settrace''가능합니다 + – DeepSpace

+0

내 특정 사용 사례에 대해이 예외 (추가 사항)가 발생하지 않았습니다. 솔루션이있는 그대로 작동합니다! –

+0

누구나 IPython qtconsole에 상응하는 아이디어가 있습니까? sys.stdout을 사용하지 않는 것으로 보입니다. ipykernel.iostream.OutStream.write 및 IPython.sys.stdout.write 시도했습니다. –

0

this article에 기반한 IPython QtConsole에서 작동하는 예제입니다. 이것은 orangeink의 솔루션 오버라이드 (override) 표준 출력과 함께 사용됩니다!

class SciNum: 
    """For compatibility with IPython's pretty printer: Contains a string, 
    with a REPR that allows pretty() to print without quotes, as it would 
    if using the string directly.""" 
    def __init__(self, text: str): 
     self.text = text 

    def __repr__(self): 
     return self.text 


def _print_ipython(arg, p, cycle) -> None: 
    """Uses IPython's pretty printer to modify output for a qtconsole or notebook; 
    stdout doesn't seem to work for them.""" 
    p.text(IPython.lib.pretty.pretty(SciNum(format(arg)))) 

def start() -> None: 
    if not ipython_exists: 
     return 

    ip = IPython.get_ipython() 
    # We only need to handle IPython separately if in a Qtconsole or Notebook. 
    if isinstance(ip, IPython.terminal.interactiveshell.TerminalInteractiveShell): 
     return 

    text_formatter = ip.display_formatter.formatters['text/plain'] 

    text_formatter.for_type(float, _print_ipython) 
    text_formatter.for_type(int, _print_ipython)