문제

몇 달 전에 나는 a를 썼다 블로그 게시물 표준 Python 대화식 통역사에서 탭 완성을 달성하는 방법에 대해 자세히 설명합니다. iPyThon 유니 코드 문제로 인해 때때로 표준 통역사로 전환해야한다는 점을 감안할 때 엄청나게 편리하다는 것을 알았습니다.

최근에 나는 OS X에서 약간의 작업을 수행했습니다. 불만에 대한 스크립트는 OS X의 터미널 응용 프로그램에서는 작동하지 않는 것 같습니다. OS X에서의 경험을 가진 여러분 중 일부가 터미널에서도 작동 할 수 있도록 문제를 해결하는 데 도움이되기를 바랍니다.

아래 코드를 재현하고 있습니다

import atexit
import os.path

try:
    import readline
except ImportError:
    pass
else:
    import rlcompleter

    class IrlCompleter(rlcompleter.Completer):
        """
        This class enables a "tab" insertion if there's no text for
        completion.

        The default "tab" is four spaces. You can initialize with '\t' as
        the tab if you wish to use a genuine tab.

        """

        def __init__(self, tab='    '):
            self.tab = tab
            rlcompleter.Completer.__init__(self)


        def complete(self, text, state):
            if text == '':
                readline.insert_text(self.tab)
                return None
            else:
                return rlcompleter.Completer.complete(self,text,state)


    #you could change this line to bind another key instead tab.
    readline.parse_and_bind('tab: complete')
    readline.set_completer(IrlCompleter('\t').complete)


# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
    readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))

내 블로그 게시물의 버전에서 약간 편집하여 IrlCompleter 터미널의 탭 키에 의해 출력되는 것으로 보이는 실제 탭으로 초기화됩니다.

도움이 되었습니까?

해결책

더 많은 GPL 코드를 사용하지 않으려면 Apple에는 실제 읽기가 포함되어 있지 않습니다. 대신 BSD 라이센스를 사용합니다 libedit, 이것은 대부분 읽기 호환됩니다. 완료하려는 경우 자신의 파이썬 (또는 Fink 또는 MacPort를 사용)을 구축하십시오.

다른 팁

이것은 Leopard의 파이썬에서 작동해야합니다.

import rlcompleter
import readline
readline.parse_and_bind ("bind ^I rl_complete")

반면에 이것은 그렇지 않습니다.

import readline, rlcompleter
readline.parse_and_bind("tab: complete")

~/.pythonrc.py에 저장하고 .bash_profile에서 실행하십시오.

export PYTHONSTARTUP=$HOME/.pythonrc.py

다음은 한 번의 Windows/OS X/Linux 용로드 탭 완료의 전체 크로스 플랫폼 버전입니다.

#Code  UUID = '9301d536-860d-11de-81c8-0023dfaa9e40'
import sys
try:
        import readline
except ImportError:
        try:
                import pyreadline as readline
        # throw open a browser if we fail both readline and pyreadline
        except ImportError:
                import webbrowser
                webbrowser.open("http://ipython.scipy.org/moin/PyReadline/Intro#line-36")
                # throw open a browser
        #pass
else:
        import rlcompleter
        if(sys.platform == 'darwin'):
                readline.parse_and_bind ("bind ^I rl_complete")
        else:
                readline.parse_and_bind("tab: complete")

에서 http://www.farmckon.net/?p=181

이것은 Linux Bash와 OS X 10.4에서 나를 위해 작동합니다.

import readline
import rlcompleter
readline.parse_and_bind('tab: complete')

위를 시도한 후에도 여전히 작동하지 않는 경우 쉘에서 실행하십시오.

sudo easy_install readline

그런 다음 생성하십시오 ~/.profile 내용으로 파일 :

export PYTHONSTARTUP=$HOME/.pythonrc.py

그리고 a ~/.pythonrc.py 내용으로 파일 :

try:
    import readline
except:
    print ("Module readline is not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

감사합니다 스티븐 밤 포드 Easy_Install 팁 및 니콜라스 파일 내용의 경우.

Libedit (Mac OS 세미 리드 라인)에게 문서화 된 방법은 Readline에서 "libedit"입니다.문서: Pass # Mac Case Else : Pass # gnu readline case

FreeBSD에서 Python (2 및 3)을 다루는 많은 문제에 충돌 한 후 마침내 Libedit을 Python의 불신자로 직접 사용하는 데 적절한 확장을 얻었습니다.

Libedit/Readline의 기본 문제는 Python의 완료와 입력이 GNU Readline에 크게 구부러 졌다는 것입니다. 슬프게도, 이것은 실제로 특히 좋은 인터페이스가 아닙니다. C에서는 거대한 수의 글로벌이 필요하며 "인스턴스"기준으로 잘 작동하지 않습니다.

해결책:

https://github.com/mark-nicholson/python-editline

이것은 측면의 읽기 라인 접착제가 아닌 실제 "libedit"인터페이스를 사용하여 Libedit에 직접 연결되는 진정한 별도의 파이썬 확장자입니다.

Ubuntu, FreeBSD, OpenBSD, NetBsd 및 MacOS에서 꽤 철저히 테스트했습니다. 결과는 ReadMe에 게시됩니다. C 코드는 매우 깨끗하고 Python의 Readline.c 모듈과 달리 플랫폼 의존 비트가 거의 없습니다.

참고 : Python3> 3.2에서 작동합니다. 다른 스크립트에서 'Readline import'에 대한 드롭 인 대체는 아니지만 해당 스크립트를 쉽게 조정할 수 있습니다. readline.so와 공존 할 수 있습니다-선택을 가능하게하는 sitecustomize.py 파일에 대한 코드가 있습니다. 확장 자체에 내장 된 사용자 정의 내장 또는 리베이트 배포 'libedit.so'를 사용할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top